Python-文件的讀寫

文件的讀入

open() 函數(shù)

open(name, mode)

name:需要訪問文件名稱的字符串值

mode:mode決定了打開文件的模式

常用的打開文件的模式

模式 描述
r 以只讀方式打開文件。文件的指針將會放在文件的開頭。這是默認(rèn)模式。
w 打開一個文件只用于寫入。如果該文件已存在則打開文件,并從開頭開始編輯,即原有內(nèi)容會被刪除。如果該文件不存在,創(chuàng)建新文件。
a 打開一個文件用于追加。如果該文件已存在,文件指針將會放在文件的結(jié)尾。也就是說,新的內(nèi)容將會被寫入到已有內(nèi)容之后。如果該文件不存在,創(chuàng)建新文件進行寫入。
r+ 打開一個文件用于讀寫。文件指針將會放在文件的開頭。
w+ 打開一個文件用于讀寫。如果該文件已存在則打開文件,并從開頭開始編輯,即原有內(nèi)容會被刪除。如果該文件不存在,創(chuàng)建新文件。
a+ 打開一個文件用于讀寫。如果該文件已存在,文件指針將會放在文件的結(jié)尾。文件打開時會是追加模式。如果該文件不存在,創(chuàng)建新文件用于讀寫。

讀取整個文件

新建一個文件,命名為poem.txt

Who has seen the wind?
Neither I nor you;
But when the leaves hang trembling,
The wind is passing through.

在相同文件夾下創(chuàng)建一個py文件,命名為poem_reader.py

with open('poem.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())

關(guān)鍵字with在不再需要訪問文件后將其關(guān)閉

使用read()到達(dá)文件末尾時返回一個空字符從而顯示出來一個空行,用rstrip()可以刪除字符串末尾的空白

讀取文本文件時,Python將其中的所有文本都解讀為字符串。

image-20211223141513456

如果需要讀取的文件和程序不在同一個文件夾,要寫出文件所在路徑。

file_path = 'D:\py\poem.txt'
with open(file_path) as file_object:
    contents = file_object.read()
    print(contents.rstrip())
image-20211223142242506

逐行讀取

file_path = 'D:\py\poem.txt'
with open(file_path) as file_object:
    for line in file_object:
        print(line.rstrip())
image-20211231153037052

文件內(nèi)容的使用

file_path = 'D:\py\poem.txt'
with open(file_path) as file_object:
    lines = file_object.readlines()

poem_string = ''

for line in lines:
    poem_string += line.strip()
poem_string1 = poem_string[:22]
print(poem_string1)
print(len(poem_string1))
image-20211231161518424

strip() 方法用于移除字符串頭尾指定的字符(默認(rèn)為空格或換行符)或字符序列,該方法只能刪除開頭或是結(jié)尾的字符,不能刪除中間部分的字符

文件的寫入

寫入空文件

可以創(chuàng)建新的py文件,這里使用之前的poem_reader.py

filename = "poem.txt"
with open(filename,'w') as file_object:
    file_object.write("Who has seen the wind?")

with open(filename, 'r') as file_object:
    contents = file_object.read()
    print(contents)
image-20220106135214863

以寫入('w')模式打開文件時,如果指定的文件已經(jīng)存在,Python將在返回文件對象前清空該文件。

寫入多行

filename = "poem.txt"
with open(filename,'w') as file_object:
    file_object.write("Who has seen the wind?\n")
    file_object.write("Neither I nor you;\n")

with open(filename, 'r') as file_object:
    contents = file_object.read()
    print(contents)
image-20220106142238073

附加到文件

打開文件時指定實參'a',將內(nèi)容附加到文件末尾,而不是覆蓋文件原來的內(nèi)容。

filename = "poem.txt"
with open(filename,'a') as file_object:
    file_object.write("But when the leaves hang trembling,\n")
    file_object.write("The wind is passing through.\n")

with open(filename, 'r') as file_object:
    contents = file_object.read()
    print(contents)
image-20220106144423318
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容