python按行讀取文件


轉載:https://blog.csdn.net/qdPython/article/details/106160272

在本文中,我們將討論在Python中逐行讀取文件的不同方法。

假設我們在與python腳本相同的目錄中有一個data.txt文件。讓我們看看如何逐行閱讀其內容。

小型文件的解決方案:使用readlines()獲取文件中所有行的列表

第一個基本且效率低下的解決方案是使用 readlines() 函數。

如果我們有一個小文件,則可以在文件處理程序上調用readlines(),它將整個文件內容讀取到內存中,然后將其拆分為單獨的行,並返回文件中所有行的列表。除最后一行外,列表中的所有行將在末尾包含換行符。
例如,

# Open file    
fileHandler  =  open  ("data.txt",  "r")
# Get list of all lines in file
listOfLines  =  fileHandler.readlines()
# Close file
fileHandler.close()

它將返回文件中的行列表。我們可以遍歷該列表,並剝離()新行字符,然后打印該行,即

# Iterate over the lines
for  line in  listOfLines:
    print(line.strip())

輸出:

'''
遇到問題沒人解答?小編創建了一個Python學習交流QQ群:531509025
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書!
'''
Hello
This is  a  sample
file that contains is
some text
is
like  123

但是,如果文件很大,則會消耗大量內存,因此,如果文件很大,最好避免使用此解決方案。

讓我們看一些有效的解決方案,

使用readline()逐行讀取文件

讀取大文件時,有效的方法是逐行讀取文件,而不是一次性讀取所有數據。
讓我們將readline()函數與文件處理程序一起使用,即

lineStr  =  fileHandler.readline()

readline()返回文件中的下一行,該行的末尾將包含換行符。另外,如果到達文件末尾,則它將返回一個空字符串。
現在讓我們看看如何使用readline()逐行讀取文件內容

'''
遇到問題沒人解答?小編創建了一個Python學習交流QQ群:531509025
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書!
'''
# Open file        

fileHandler  =  open  ("data.txt",  "r")
while  True:
    # Get next line from file
    line  =  fileHandler.readline()
    # If line is empty then end of file reached
    if  not  line  :
        break;
    print(line.strip())
    # Close Close    
fileHandler.close()

輸出:

Hello
This is  a  sample
file that contains is
some text
is
like  123

使用上下文管理器逐行讀取文件(帶塊)

當我們打開文件時,我們也需要關閉它。如果我們忘記關閉,那么它將在例如對函數結尾處的文件引用的最后一個引用被破壞時自動關閉。但是,即使文件相關的工作已經完成,如果我們有一個大型功能不會很快結束該怎么辦。在這種情況下,我們可以使用上下文管理器自動清除諸如文件關閉之類的內容。
例如,

Hello
This is  a  sample
file that contains is
some text
is
like  123

在這種情況下,當控制脫離塊時,文件將自動關閉。即使由於某些異常而出現阻塞。

使用上下文管理器(帶塊)獲取文件中的行列表

讓我們遍歷文件中的所有行並創建行列表,即

'''
遇到問題沒人解答?小編創建了一個Python學習交流QQ群:531509025
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書!
'''
# Get the all the lines in file in a list

listOfLines  =  list()
with  open  ("data.txt",  "r")  as  myfile:
    for  line in  myfile:
        listOfLines.append(line.strip())

listOfLines列表的內容為

['Hello',  'This is a sample',  'file that contains is',  'some text',  'is',  '',  'like 123']

使用上下文管理器和while循環逐行讀取文件的內容

讓我們使用上下文管理器和while循環遍歷文件中的各行,即

# Open file

with  open("data.txt",  "r")  as  fileHandler:
    # Read next line
    line  =  fileHandler.readline()
    # check line is not empty
    while  line:
         print(line.strip())
         line  =  fileHandler.readline()

列表的內容將是.

Hello
This is  a  sample
file that contains is
some text
is
like  123

完整的示例如下,

'''
遇到問題沒人解答?小編創建了一個Python學習交流QQ群:531509025
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書!
'''
def main():
    print("****Read all lines in file using readlines() *****")
    # Open file
    fileHandler = open("data.txt", "r")
    # Get list of all lines in file
    listOfLines = fileHandler.readlines()
    # Close file
    fileHandler.close()
    # Iterate over the lines
    for line in listOfLines:
        print(line.strip())
    print("****Read file line by line and then close it manualy *****")
    # Open file
    fileHandler = open("data.txt", "r")
    while True:
    # Get next line from file
        line = fileHandler.readline()
        # If line is empty then end of file reached
        if not line:
            break;
        print(line.strip())
    # Close Close
    fileHandler.close()
    print("****Read file line by line using with open() *****")
    # Open file
    with open("data.txt", "r") as fileHandler:
        # Read each line in loop
        for line in fileHandler:
            # As each line (except last one) will contain new line character, so strip that
            print(line.strip())
    print("****Read file line by line using with open *****")
    # Get the all the lines in file in a list
    listOfLines = list()
    with open("data.txt", "r") as myfile:
        for line in myfile:
            listOfLines.append(line.strip())
    print(listOfLines)
    print("****Read file line by line using with open() and while loop *****")
    # Open file
    with open("data.txt", "r") as fileHandler:
        # Read next line
        line = fileHandler.readline()
        # check line is not empty
        while line:
            print(line.strip())
            line = fileHandler.readline()


if __name__ == '__main__':
    main()

輸出:

****Read all lines in file using readlines() *****
Hello
This is a sample
file that contains is
some text
is
 
like 123
****Read file line by line and then close it manualy *****
Hello
This is a sample
file that contains is
some text
is
 
like 123
****Read file line by line using with open() *****
Hello
This is a sample
file that contains is
some text
is
 
like 123
****Read file line by line using with open *****
['Hello', 'This is a sample', 'file that contains is', 'some text', 'is', '', 'like 123']
****Read file line by line using with open() and while loop *****
Hello
This is a sample
file that contains is
some text
is
 
like 123

 

參考:

https://www.cnblogs.com/Kingfan1993/p/9570079.html

https://www.jianshu.com/p/3d3e17fa5a14


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM