- Readlines()是 Python 中使用的一個函數,用於一次性逐行讀取特定的文件。
- 在使用蠻力方法讀取文件以及使用循環和不同的迭代時,這對於降低時間複雜度非常有用。
- 它是一個一行代碼和簡單的函數,比僅僅讀取一個文件使用很多循環要好得多。
- 在 C 編程中,讀取文件是一項相當艱巨的任務,但是由於 Python 中的
readlines()
函數,它非常容易實現。 readlines()
函數只從給定文件中讀取一個完整的行;讀取後,它以列表的形式返回包含所有元素的整行。- 如果我們想以正常讀取模式打開文件,readline()函數將返回字符串。
- 如果我們想以二進制模式打開文件,那麼 readline()函數將返回一個二進制對象。
- 在行尾追加一個換行符(” \n “)也是非常有益的。
- 這個
readlines()
函數最適合小文件,包含的數據較少,可以在更短的時間內輕鬆讀取整個文件。 - 它首先一次性將文件內容讀入內存,然後將它們分成不同的行。藉助
strip()
函數,我們可以遍歷由 readline()函數生成的整個列表,通過使用strip()
函數,我們可以剝離換行符’ \n ‘字符。
Python 文件概念
Python 編程語言有各種內置的功能用於寫、創建、和讀文件。Python 中處理兩類文件,一類是普通文本文件,第二類是以二進制語言為主寫的二進制文件,即 0 和 1。
- 文本文件:這些文件包含文本形式的數據,以一個名為 EOL(行尾)的特殊字符結束,默認情況下是 Python 中的新行字符(‘ \n ‘)。
- 二進制文件:這些類型的文件包含二進制序列形式的數據,主要由 0 和 1 組成。
要在文件中執行的某些基本步驟:
打開文件:打開文件是使用 open()函數完成的;使用此函數時,我們必須將文件名和訪問模式作為參數傳遞。
這裡的文件訪問模式如下:
- 只讀(r ): 用於從文件中讀取數據。它正在定位文件的開頭。如果提到的文件不存在,它將產生輸入/輸出錯誤。只讀是打開文件的默認模式;使用此模式時,我們無法編輯文件的數據,也無法將其寫入文件。
- 只寫(‘ w ‘ ): 用於將數據寫入文件,定位文件開頭。如果提到的文件不存在,那麼它將產生輸入/輸出錯誤。使用此模式時,我們無法從文件中讀取數據。
- 讀寫(‘ r+ ‘ ): 此模式用於從文件中寫入和讀取數據。如果我們將其與之前的模式進行比較,我們可以區分出我們不能在只讀模式下寫入文件,但是我們可以在該模式下讀寫文件。
例如,如果我們有一個名為 hello.txt 的文件,並且我們想以寫模式打開它,那麼我們可以將它用作:
文件 1 =打開(「hello.txt」,「w」)
關閉文件:關閉功能用於釋放文件所需的內存空間;當不再需要該文件時,或者當我們想要關閉整個文件並且想要以不同的模式打開該文件時,使用該方法。它是通過使用 close()函數來執行的,在這個函數內部,我們不需要傳遞任何參數;這個函數可以使用文件名訪問,並由點關閉函數提供。
例如,如果我們有一個名為 hello.txt 的文件,並且我們想以寫模式打開它,那麼我們可以將它用作:
File1 = open ( ” hello.txt ” , ” w ” )
File1.close ( )
寫入文件:顧名思義,我們可以很容易地預測在這個方法中,我們需要在文件中寫入什麼。有兩種方法可以寫入文件:
- Write ( ): 在這個函數中,我們必須傳遞一個單獨的參數,也就是我們想要插入到文件中的字符串。
例如,如果我們有一個名為 hello.txt 的文件,並且我們想以寫模式打開它,那麼我們可以將其用作:
file 1 = open(「hello . txt」,「w」)
file 1 . write(str)
這裡,str 是我們想插入到文件中的字符串。 - writeline():在這個函數中,我們必須傳遞一個數組或者一個由多個字符串組成的列表。它用於一次向文件中插入多個不同的字符串。
例如,如果我們有一個名為 hello.txt 的文件,並且我們想以寫模式打開它,那麼我們可以將它用作:
file 1 = open(「hello . txt」,「w」)
file 1 . write lines(S)表示 S = [ str1,str2,str3 ]
從文件中讀取:同樣,在這個中,我們可以預測我們在這個中要做什麼;即使在本教程中,我們也將詳細閱讀其中一種閱讀方法。在這種方法中,我們需要從特定的文件中讀取數據。從文件中讀取數據有三種方法:
- Read ( ): 以字符串的形式返回讀取的位元組。讀取
n
個位元組;如果未指定 n,則讀取整個文件。 - Readline ( ): 讀取文件的一行,並以字符串的形式返回。對於指定的 n,讀取最多
n
個位元組。readline()函數不會一次讀取多行;即使 n 超過,它也只讀取一行。Readline()函數讀取文件的一行並以字符串形式返回。它採用整數值 n 作為參數來讀取一次讀取的字符數。Readline()方法在從非常大的文件中讀取數據時非常有效,因為它逐行讀取數據,並在屏幕上返回和打印。Readline()返迴文件的下一行,最後包含一個換行符。此外,如果到達文件的末尾,它將返回一個空字符串。 - readline():讀取所有行,並將其作為列表中的字符串元素返回。Readlines()用於一次性讀取所有行,然後將它們作為列表中的字符串元素返回。這個函數可以用於小文件,因為它將整個文件內容讀入內存,然後將其拆分成單獨的行。使用
strip()
函數,我們可以遍歷列表,並使用strip()
函數刪除換行符’ \n ‘。
現在讓我們藉助一個例子來詳細理解讀取文件的概念:
用 Python 讀取文件的示例:
例 1:
使用 readlines()功能讀取文件
# Python program to implement the file concept using readlines ( ) for reading a file
Fruits = ["Apple\n", "Orange\n", "Banana\n"]
# writing to file
file = open('hello.txt', 'w')
file.writelines(Fruits) # writelines is used to write the data into the file in # the form of a list, by inserting multiple values at the same time,
# here, we are taking the hello.txt file
file.close() # This instruction is used to close the file, i.e., hello.txt
# Using readlines()
file = open('hello.txt', 'r')
Statements = file.readlines()
count = 0
# Strips the newline character
for line in Statements: # Using for loop to print the data of the file
count = count + 1
print("Statement{}: {}".format(count, line.strip()))
上例的輸出:
例 2:
使用 readline()功能讀取文件
# Python program to implement the file concept using readline() for reading a file
Fruit = [ "Apple\n" , "Graphs\n" , "Mango\n" , "Orange\n" , "Kiwi\n" ]
# Writing to a file
file1 = open('new.txt', 'w')
file1.writelines((Fruit)) # writelines is used to write the data into the file in # the form of list, by inserting multiple values at a same time,
# here we are taking new.txt file
file1.close() # This instruction is used to close the file, i.e., hello.txt
# Using readline()
file1 = open('new.txt', 'r')
count = 0
while True:
count = count + 1
# Get next line from file
s = file1.readline()
# if line is empty
# end of file is reached
if not s:
break
print("Statement{}: {}".format(count, s.strip()))
file1.close()
上例的輸出:
例 3:
使用簡單 for
循環讀取文件:
在這個方法中,我們沒有使用 readline()函數,甚至沒有使用 readline()函數,因為我們已經在上面的例子中看到了這兩個函數的使用;在這個方法中,我們將使用 for
循環來打印文件的數據。我們將迭代文件的對象,並逐行讀取文件,儘管我們使用的是一些 python 預定義的內置函數。使用這些內置的 Python 函數,我們可以很容易地使用 for
循環隱式迭代文件對象,並結合使用 iterable 對象。
## Python program to implement the file concept using the simple for loop for reading a file
Fruits = ["Apple \n", " Orange \n", "Banana \n", "Mango\n", "Pineapple\n" ]
# Writing to file
file2 = open('file2.txt', 'w')
file2.writelines(Fruits) # writelines is used to write the data into the file in
# the form of list, by inserting multiple values at a same time,
# here we are taking file2.txt file
file2.close() # This instruction is used to close the file, i.e., hello.txt
# Opening file
file2 = open('file2.txt', 'r')
count = 0
# Using for loop
print("Using for loop")
for line in file2:
count = count + 1
print("Statement{}: {}".format(count, line.strip()))
# Closing files
file2.close()
上例的輸出:
例 4:
使用『with』語句讀取文件:
如果我們注意到上面 3 個例子,我們可以很容易地觀察到,每當文件需要打開時,那麼它就需要關閉;如果我們不關閉文件,那麼它將在程序中產生幾個錯誤,因為許多更改在文件中沒有完成,或者直到我們不關閉文件才生效。
因此,為了克服這個問題,我們將使用「with」語句,它主要用於 Python 中的異常處理,以使代碼更加清晰和易讀。在這裡,在這個例子中,你可以很容易地觀察到,我們沒有使用 file.close()函數,一次又一次地,為了防止文件,使用它可以用語句自動完成。因此,它減少了代碼行,使程序運行更快,實現更高效。
# Python program to implement the file concept using with statement for reading a file
Veges = ["Potato\n", "Onion\n", "Tomamto\n"]
# Writing to file
with open("file3.txt", "w") as file:
file.writelines(Veges) # writelines is used to write the data into the file in
# the form of list, by inserting multiple values at a same time,
# here we are taking file3.txt file
# using readlines()
count = 0
print("Using readlines()")
with open("file3.txt") as file:
Statements = file.readlines()
for line in Statements:
count = count + 1
print("Satement{}: {}".format(count, line.strip()))
# Using readline()
count = 0
print("\nUsing readline()")
with open("file3.txt") as file:
while True:
count = count + 1
line = file.readline()
if not line:
break
print("Statement{}: {}".format(count, line.strip()))
# Using for loop
count = 0
print("\n Using for loop")
with open("file3.txt") as file:
for line in file:
count = count + 1
print("Statements{}: {}".format(count, line.strip()))
上例的輸出:
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/250625.html