python 讀取文件函數


python 讀取文件函數

覺得有用的話,歡迎一起討論相互學習~


我的微博我的github我的B站

感謝莫煩老師
詳情

讀取文件內容 file.read()

  • 使用 file.read() 能夠讀取到文本的所有內容.
file= open('my file.txt','r')
content=file.read()  
print(content)

""""
This is my first test.
This is the second line.
This the third line.
This is appended file.    
""""

按行讀取 file.readline()

  • 如果想在文本中一行行的讀取文本, 可以使用 file.readline(), file.readline() 讀取的內容和你使用的次數有關, 使用第二次的時候, 讀取到的是文本的第二行, 並可以以此類推:
file= open('my file.txt','r')
content=file.readline()  # 讀取第一行
print(content)

""""
This is my first test.
""""

second_read_time=file.readline()  # 讀取第二行
print(second_read_time)

"""
This is the second line.
"""

讀取所有行 file.readlines()

  • 如果想要讀取所有行, 並可以使用像 for 一樣的迭代器迭代這些行結果, 我們可以使用 file.readlines(), 將每一行的結果存儲在 list 中, 方便以后迭代.
file= open('my file.txt','r')
content=file.readlines() # python_list 形式
print(content)

""""
['This is my first test.\n', 'This is the second line.\n', 'This the third line.\n', 'This is appended file.']
""""

# 之后如果使用 for 來迭代輸出:
for item in content:
    print(item)

"""
This is my first test.

This is the second line.

This the third line.

This is appended file.
"""


免責聲明!

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



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