如何在Python中讀取文字檔案?
文字檔案是包含簡單文字的檔案。Python 提供內建函式來讀取、建立和寫入文字檔案。我們將討論如何在 Python 中讀取文字檔案。
在 Python 中讀取文字檔案有三種方法:
read() − 此方法讀取整個檔案並返回包含檔案所有內容的單個字串。
readline() − 此方法從檔案中讀取一行並將其作為字串返回。
readlines() − 此方法讀取所有行並將其作為字串列表返回。
在Python中讀取檔案
假設有一個名為“myfile.txt”的文字檔案。我們需要以讀取模式開啟該檔案。“r”指定讀取模式。可以使用 open() 開啟檔案。傳遞的兩個引數是檔名和需要開啟檔案的模式。
示例
file=open("myfile.txt","r")
print("read function: ")
print(file.read())
print()
file.seek(0) #Take the cursor back to begining of the file since the read() takes the cursor to the end of file
print("readline function:")
print(file.readline())
print()
file.seek(0) #Take the cursor back to beginning of file
print("readlines function:")
print(file.readlines())
file.close()輸出
read function: This is an article on reading text files in Python. Python has inbuilt functions to read a text file. We can read files in three different ways. Create a text file which you will read later. readline function: This is an article on reading text files in Python. readlines function: ['This is an article on reading text files in Python.\n', 'Python has inbuilt functions to read a text file.\n', 'We can read files in three different ways.\n', 'Create a text file which you will read later.']
從輸出中可以清楚地看出:
read() 函式讀取並返回整個檔案。
readline() 函式讀取並僅返回一行。
readlines() 函式讀取並返回所有行作為字串列表。
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP