本文實例講述了python文件寫入的用法。分享給大家供大家參考。具體分析如下:
Python中wirte()方法把字符串寫入文件,writelines()方法可以把列表中存儲的內容寫入文件。
1
2
3
4
|
f = file ( "hello.txt" , "w+" ) li = [ "hello world\n" , "hello china\n" ] f.writelines(li) f.close() |
文件的內容:
1
2
|
hello world hello china |
write()和writelines()這兩個方法在寫入前會清除文件中原有的內容,再重新寫入新的內容,相當于“覆蓋”的方法。如果需要保留文件中原有的內容,只是需要追加新的內容,可以使用“a+”模式打開文件。
1
2
3
4
|
f = file ( "hello.txt" , "a+" ) new_context = "goodbye" f.write(new_content) f.close() |
此時hello.txt中的內容如下所示:
1
2
3
|
hello world hello china goodbye |
實踐:
1
2
3
4
5
6
7
8
9
10
|
>>> 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() |
結果:
1
2
3
|
hello world hello china goodbyegoodbye |
希望本文所述對大家的Python程序設計有所幫助。