Python3基礎之(十 七)讀寫檔案3
阿新 • • 發佈:2018-11-17
一、讀取檔案內容 file.read()
上一節我們講了,寫檔案用的是'w'
和'a'
,那麼今天來看看讀取檔案怎麼做
使用 file.read() 能夠讀取到文字的所有內容.
if __name__=='__main__':
file=open('my file.txt','r')
content=file.read()
print(content)
我們可以看出,無論是讀取還是寫入,都需要先將檔案open
一下,只不過讀的時候後面引數是'r'
,寫的時候後面引數是'w'
或者'a'
。
二、按行讀取 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.
"""