十八 python 對檔案讀寫

2021-07-05 05:26:52 字數 1660 閱讀 4137

檔案的讀寫按道理是應該在前面有所提及的,居然忘了,主要是比較簡單,所以一直不想寫,現今補上這一部分的內容。

方法一:

**如下:

f = open("foo.txt") # 返回乙個檔案物件

line = f.readline() # 呼叫檔案的 readline()方法

while

line:

print line, # 後面跟 ',' 將忽略換行符

# print(line, end = '')   # 在 python 3中使用

line = f.readline()

f.close()

方法二:

複製** **如下:

forline

inopen("foo.txt"):

print line,

方法三:

複製** **如下:

f = open("c:\\1.txt","r")

lines = f.readlines()#讀取全部內容

forline

inlines

print line

wirte()方法把字串寫入檔案,writelines()方法可以把列表中儲存的內容寫入檔案。

f=file("hello.txt","w+")

li=["hello world\n","hello china\n"]

f.writelines(li)

f.close()

檔案的內容:

hello world

hello china

write()和writelines()這兩個方法在寫入前會清除檔案中原有的內容,再重新寫入新的內容,相當於「覆蓋」的方法。如果需要保留檔案中原有的內容,只是需要追加新的內容,可以使用「a+」模式

開啟檔案。

f=file("hello.txt","a+")

new_context="goodbye"

f.write(new_content)

f.close()

此時hello.txt檔案中的內容:

hello world

hello china

goodbye

實踐:

>>> f=file("hello.txt","w+")

>>> li=["hello world\n","hello china\n"]

>>> f.writelines(li)

>>> f.close()

>>>

>>> f=file("hello.txt","a+")

>>> new_context="goodbye"

>>> f.write(new_content)

>>> f.write(new_content)

>>> f.close()

則結果為:

hello world

hello china

goodbyegoodbye

python對檔案的讀寫操作

python對多個json物件的json檔案讀取 參考部落格 with open data path,r encoding utf 8 as f for item in jsonlines.reader f item是按行讀取的乙個json物件 print item python寫入檔案 a 表示不...

python中對檔案的讀寫

檔案 將資料儲存到硬碟中 資料持久化 開啟檔案 open 檔案路徑,訪問模式 w write 寫入模式,只能寫,不能讀 f open 123.txt w 寫入資料 只能是字串 f.write hello world 關閉檔案 檔案操作完必須要關閉,否則檔案占用記憶體將無法釋放 記憶體洩漏 明知沒有用...

Python筆記 對檔案的讀寫操作

寫入檔案 f open my path my file.txt w f.write hello there f.close with語法,該語法會在你使用完檔案後自動關閉該檔案 with open my path my file.txt r as f file data f.read 在之前的 中,...