Published 4月 12, 2020 by with 0 comment

Automate The Boring Stuff With Python - Chapter 8 – 讀寫文件

今天是看這本書Automate the Boring Stuff with Python(Python編程快速上手--讓繁瑣工作自動化)
第8章節(Input Validation)所做的練習

這章主要講使用Python在硬碟上創建, 讀取和保存文件


依據Windows或Linux不同, 路徑的表達方式也不樣
Windows是D:\Tech\Blog\Python
Linux是root/Tech/Blog/Python
使用os.path.join 可以讓python自動依照作業系統的不同, 將各參數組合並返回一個路徑
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
>>>


os.getcwd() 顯示當前的工作目錄
os.chdir() 移動到該工作目錄
>>> import os
>>> os.getcwd()
'C:\\Users\\Peter\\AppData\\Local\\Programs\\Python\\Python37'
>>> os.chdir('c:\\Windows\\System32')
>>> os.getcwd()
'c:\\Windows\\System32'
>>>


os.makedirs() 創建文件夾
>>> import os
>>> os.makedirs('C:\\Users\\Peter\\AppData\\Local\\Programs\\Python\\Python37\\test1')
>>>


os.path.abspath() 處理絕對路徑
os.path.relpath() 處理相對路徑, 代入兩個參數, 第一個是目的地目錄, 第二個是起點目錄,若沒有提供第二參數, 則使用當前的工作目錄.
>>> import os
>>> os.path.abspath('.')
'C:\\Users\\Peter\\AppData\\Local\\Programs\\Python\\Python37'
>>>
>>> os.path.relpath('C:\\Users\\Peter', 'c:\\Windows')
'..\\Users\\Peter'
>>>


os.path.dirname(path) 顯示path參數中最後一個斜槓之前的所有內容 (一個檔案的路徑名稱)
os.path.basename(path) 顯示path參數中最後一個斜槓之後的所有內容 (檔名)
>>> import os
>>> path = 'C:\\Windows\\system32\\calc.exe'
>>> os.path.dirname(path)
'C:\\Windows\\system32'
>>> os.path.basename(path)
'calc.exe'
>>>


os.path.split() 可以同時取得一個檔案的路徑名稱和檔名, 返回是元組()
>>> import os
>>> path = 'C:\\Windows\\system32\\calc.exe'
>>> os.path.split(path)
('C:\\Windows\\system32', 'calc.exe')
>>>


os.path.sep 可以將一路徑分割為列表
>>> import os
>>> path = 'C:\\Windows\\system32\\calc.exe'
>>> path.split(os.path.sep)
['C:', 'Windows', 'system32', 'calc.exe']
>>>


os.path.getsize() 取得參數中檔案的大小
os.listdir(path) 用列表(list)的方式, 列出該目錄中所有目錄及文件名
>>> import os
>>> path = 'C:\\Windows\\system32\\calc.exe'
>>> os.path.getsize(path)
918528
>>>
>>> os.listdir('D:\Tech\Blog\Python\Automate The Boring Stuff With Python')
['.idea', 'Automate_the_Boring_Stuff_onlinematerials_v.2', 'Automate_the_Boring_Stuff_onlinematerials_v.2.zip', 'C2.jpg', 'C5.jpg', 'Chapter 1', 'Chapter 11', 'Chapter 18', 'Chapter 2', 'Chapter 3', 'Chapter 4', 'Chapter 5', 'Chapter 6', 'Chapter 7', 'Chapter 8', 'CH_12.py']
>>>


取得這個目錄下所有檔案的總字節數
>>> import os
>>> totalSize = 0
>>> for filename in os.listdir('D:\Tech\Blog\Python\Automate The Boring Stuff With Python'):    # 列出該目錄下所有的子目錄與檔案名
    totalSize = totalSize + os.path.getsize(os.path.join('D:\Tech\Blog\Python\Automate The Boring Stuff With Python', filename))    #將路徑及檔名結合, 並取其檔案大小
>>> print(totalSize)
8880693
>>>


os.path.exists(path) 若path參數所指定的文件或目錄存在, 則回應True, 反之回應False.
os.path.isfile(path) 若path參數所指定的文件存在, 則回應True, 反之回應False.
os.path.isdir(path) 若path參數所指定的目錄存在, 則回應True, 反之回應False.
>>> import os
>>> os.path.exists('C:\\Windows\\system32')
True
>>>
>>> os.path.isfile('C:\\Windows\\system32\\calc.exe')
True
>>>
>>> os.path.isdir('C:\\Windows\\system32')
True
>>>


文件的讀寫
調用open()函數, 返回一個file對象. open()第二個參數'r'為讀取模式(預設), 'w'為寫入模式, 'a'為添加模式.
調用file對象的read()或write()
調用file對象的close(), 關閉該文件.
>>> import os
>>> helloFile = open('D:\Tech\Blog\Python\Automate The Boring Stuff With Python\Chapter 8\8_2.txt')
>>> helloFileRead = helloFile.read()
>>> helloFileRead
'Hello World!\nHello World! - 2\nHello World! - 3'
>>> print(helloFileRead)
Hello World!
Hello World! - 2
Hello World! - 3
>>> helloFile.close()
>>>


readlines()讀取整個檔案所有行,儲存在一個列表(list)變數中,每行作為一個元素,但讀取大檔案會比較佔記憶體讀取文件.
>>> import os
>>> helloFile = open('D:\Tech\Blog\Python\Automate The Boring Stuff With Python\Chapter 8\8_2.txt')
>>> helloFileReadLines = helloFile.readlines()
>>> helloFileReadLines
['Hello World!\n', 'Hello World! - 2\n', 'Hello World! - 3']
>>> helloFile.close()
>>>


調用open()函數, 返回一個file對象. open()第二個參數'r'為讀取模式(預設), 'w'為寫入模式, 'a'為添加模式.
若對象不存在, 就會創一個新的.
先用'w' 開啟寫入模式. 用write()寫入一些內容, 並檢查內容, 再關閉檔案.
再用'a' 開啟添加模式. 用write()在原本的內容後面添加一些內容, 並檢查內容, 再關閉檔案.
>>> import os
>>> testFile = open('D:\Tech\Blog\Python\Automate The Boring Stuff With Python\Chapter 8\8_2_3.txt','w')    # 創了一個新文檔叫8_2_3.txt, 'w'為寫入模式.
>>> testFile.write('Test-1\n')    # 寫入內容, 字節數為7
7
>>> testFile.close()    # 關閉檔案
>>> testFile = open('D:\Tech\Blog\Python\Automate The Boring Stuff With Python\Chapter 8\8_2_3.txt')    #打開文檔8_2_3.txt, 預設為'r'的讀取模式.
>>> testFileContent = testFile.read()    # read 讀取內容
>>> testFile.close()    # 關閉檔案
>>> print(testFileContent)    # 檢查內容
Test-1

>>>
>>> testFile = open('D:\Tech\Blog\Python\Automate The Boring Stuff With Python\Chapter 8\8_2_3.txt', 'a')    # 打開文檔8_2_3.txt, 'a'為添加模式
>>> testFile.write('Test-2\n')    # 在原本的內容後面添加一些內容, 字節數為7
7
>>> testFile.close()    # 關閉檔案
>>> testFile = open('D:\Tech\Blog\Python\Automate The Boring Stuff With Python\Chapter 8\8_2_3.txt')    #打開文檔8_2_3.txt, 預設為'r'的讀取模式.
>>> testFileNewContent = testFile.read()    # read 讀取內容
>>> testFile.close()    # 關閉檔案
>>> print(testFileNewContent)    # 檢查新內容
Test-1
Test-2

>>>


章節8習題, 用Notepad++打下列的程式碼,
另存為8_9_3.py. 我附上中文注釋方便好讀.
# -*- coding: UTF-8 -*-
# http://juilin77.blogspot.com/
# v20200411
# Automate The Boring Stuff With Python - Chapter 8

# ========== 8.9.3 ==========
import re
import os

files = []
for file in os.listdir('.'):    # 用列表(list)的方式, 列出該目錄中所有目錄及文件名
    if file.endswith('.txt'):
        files.append(file)

userExpression = input('What RE are you looking for? :')
searchRegex = re.compile(userExpression, re.I)    # 用re.compilet傳入一個字浮串值來表示正則式.

fileList = []
for fileName in files:
    openFile = open(fileName)
    readFile = openFile.read()
    if searchRegex.search(readFile):    # 如果正則有符合文件內容, 則把檔名加進來
        fileList.append(fileName)

print(fileList)


Reference:
Automate the Boring Stuff with Python
Python編程快速上手--讓繁瑣工作自動化
ISBN-10: B01N6B9BSA
https://www.amazon.com/Python%E7%BC%96%E7%A8%8B%E5%BF%AB%E9%80%9F%E4%B8%8A%E6%89%8B-%E8%AE%A9%E7%B9%81%E7%90%90%E5%B7%A5%E4%BD%9C%E8%87%AA%E5%8A%A8%E5%8C%96-%E7%BE%8E-Al-Sweigart%EF%BC%88%E6%96%AF%E7%BB%B4%E5%8A%A0%E7%89%B9%EF%BC%89/dp/B01I0XN8XY/ref=sr_1_1?ie=UTF8&qid=1543814481&sr=8-1&keywords=9787115422699

官網:
https://automatetheboringstuff.com/


最初發表 / 最後更新: 2020.04.12 / 2020.04.12

0 comments:

張貼留言