在 Python 中, IO 模塊提供了三種 IO 操作的方法;原始二進制文件、緩衝二進制文件和文本文件。創建文件對象的規範方法是使用open()
函數。
任何文件操作都可以通過以下三個步驟來執行:
- 使用內置的 open() 功能打開文件獲取文件對象。有不同的訪問模式,您可以在使用打開()功能打開文件時指定。
- 使用從
open()
函數檢索的文件對象執行讀、寫、追加操作。 - 關閉並釋放文件對象。
正在讀取文件
文件對象包括以下從文件中讀取數據的方法。
- read(chars):從當前位置開始讀取指定數量的字符。
- readline():讀取從當前讀取位置開始直到換行符的字符。
- readlines():讀取所有行,直到文件結束,並返回一個 list 對象。
以下C:\myfile.txt
文件將用於所有讀寫文件的例子。
C:\myfile.txt
This is the first line.
This is the second line.
This is the third line.
以下示例使用read(chars)
方法執行讀取操作。
Example: Reading a File
>>> f = open('C:\myfile.txt') # opening a file
>>> lines = f.read() # reading a file
>>> lines
'This is the first line. \nThis is the second line.\nThis is the third line.'
>>> f.close() # closing file object
上圖,f = open('C:\myfile.txt')
從當前目錄打開默認讀取模式下的myfile.txt
,返回一個文件對象。 f.read()
函數讀取所有內容,直到 EOF 為字符串。如果在read(chars)
方法中指定字符大小參數,那麼它將只讀取那麼多字符。 f.close()
將沖水並關閉溪流。
閱讀一行
下面的示例演示如何從文件中讀取一行。
Example: Reading Lines
>>> f = open('C:\myfile.txt') # opening a file
>>> line1 = f.readline() # reading a line
>>> line1
'This is the first line. \n'
>>> line2 = f.readline() # reading a line
>>> line2
'This is the second line.\n'
>>> line3 = f.readline() # reading a line
>>> line3
'This is the third line.'
>>> line4 = f.readline() # reading a line
>>> line4
''
>>> f.close() # closing file object
如您所見,我們必須在'r'
模式下打開文件。readline()
方法將返回第一行,然後指向文件中的第二行。
閱讀所有行
以下使用readlines()
功能讀取所有行。
Example: Reading a File
>>> f = open('C:\myfile.txt') # opening a file
>>> lines = f.readlines() # reading all lines
>>> lines
'This is the first line. \nThis is the second line.\nThis is the third line.'
>>> f.close() # closing file object
文件對象有一個內置的迭代器。以下程序逐行讀取給定的文件,直到StopIteration
上升,即達到 EOF。
Example: File Iterator
f=open('C:\myfile.txt')
while True:
try:
line=next(f)
print(line)
except StopIteration:
break
f.close()
使用 for
循環可以輕鬆讀取文件。
Example: Read File using the For Loop
f=open('C:\myfile.txt')
for line in f:
print(line)
f.close()
Output
This is the first line.
This is the second line.
This is the third line.
讀取二進制文件
使用open()
功能中的“rb”模式讀取二進制文件,如下圖所示。
Example: Reading a File
>>> f = open('C:\myimg.png', 'rb') # opening a binary file
>>> content = f.read() # reading all lines
>>> content
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x08\x00\x00\x00\x08\x08\x06
\x00\x00\x00\xc4\x0f\xbe\x8b\x00\x00\x00\x19tEXtSoftware\x00Adobe ImageReadyq
\xc9e\x00\x00\x00\x8dIDATx\xdab\xfc\xff\xff?\x03\x0c0/zP\n\xa4b\x818\xeco\x9c
\xc2\r\x90\x18\x13\x03*8\t\xc4b\xbc\x01\xa8X\x07$\xc0\xc8\xb4\xf0>\\\x11P\xd7?
\xa0\x84\r\x90\xb9\t\x88?\x00q H\xc1C\x16\xc9\x94_\xcc\x025\xfd2\x88\xb1\x04
\x88\x85\x90\x14\xfc\x05\xe2( \x16\x00\xe2\xc3\x8c\xc8\x8e\x84:\xb4\x04H5\x03
\xf1\\ .bD\xf3E\x01\x90\xea\x07\xe2\xd9\xaeB`\x82'
>>> f.close() # closing file object
寫入文件
文件對象提供了以下寫入文件的方法。
- 寫入:將字符串寫入流,並返回寫入的字符數。
- writelines(行):向流中寫入一個行列表。每行的末尾必須有一個分隔符。
創建新文件並寫入
如果新文件不存在或覆蓋到現有文件,則創建新文件。
Example: Create or Overwrite to Existing File
>>> f = open('C:\myfile.txt','w')
>>> f.write("Hello") # writing to file
5
>>> f.close()
# reading file
>>> f = open('C:\myfile.txt','r')
>>> f.read()
'Hello'
>>> f.close()
在上面的例子中,f=open("myfile.txt","w")
語句以寫模式打開myfile.txt
,open()
方法返迴文件對象並將其分配給變量f
。 'w'
指定文件應該是可寫的。 接下來,f.write("Hello")
覆蓋myfile.txt
文件的現有內容。它返回寫入文件的字符數,在上面的例子中是 5。 最後,f.close()
關閉文件對象。
追加到現有文件
下面通過在open()
方法中傳遞'a'
或'a+'
模式,在現有文件的末尾追加內容。
Example: Append to Existing File
>>> f = open('C:\myfile.txt','a')
>>> f.write(" World!")
7
>>> f.close()
# reading file
>>> f = open('C:\myfile.txt','r')
>>> f.read()
'Hello World!'
>>> f.close()
寫多行
Python 提供了writelines()
方法,將列表對象的內容保存在文件中。 由於換行符不會自動寫入文件,因此必須作為字符串的一部分提供。
Example: Write Lines to File
>>> lines=["Hello world.\n", "Welcome to TutorialsTeacher.\n"]
>>> f=open("D:\myfile.txt", "w")
>>> f.writelines(lines)
>>> f.close()
以“w”模式或“a”模式打開文件只能寫入,不能讀取。同樣,“r”模式只允許讀,不允許寫。為了同時執行讀取/追加操作,請使用“a+”模式。
寫入二進制文件
open()
功能默認以文本格式打開文件。要以二進制格式打開文件,請將'b'
添加到模式參數中。 因此"rb"
模式以二進制格式打開文件進行讀取,而"wb"
模式以二進制格式打開文件進行寫入。與文本文件不同,二進制文件不可讀。使用任何文本編輯器打開時,數據都無法識別。
下面的代碼將數字列表存儲在二進制文件中。該列表在寫入前首先轉換為字節數組。內置函數 bytearray() 返回對象的字節表示。
Example: Write to a Binary File
f=open("binfile.bin","wb")
num=[5, 10, 15, 20, 25]
arr=bytearray(num)
f.write(arr)
f.close()
原創文章,作者:I29TS,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/128858.html