python open() 函數以指定模式打開一個文件,創建一個 file 對象,相關的方法才可以調用它進行讀寫。
w 模式表示打開一個文件只用于寫入。如果該文件已存在則打開文件,并從開頭開始編輯,即原有內容會被刪除。如果該文件不存在,創建新文件。
write() 方法用于向文件中寫入指定字符串。在文件關閉前或緩沖區刷新前,字符串內容存儲在緩沖區中,這時你在文件中是看不到寫入的內容的。
實現代碼:
1
2
3
4
|
#!/usr/bin/python # -*- coding:utf-8 -*- file = open ( 'C:/Users/Administrator/Desktop/a/b.txt' , 'w' ) file .write( '你好,\n 世界。' ) |
結果:
打開這個文本可以看到內容成功寫入。
知識點擴充:
Python批量修改文本文件內容的方法
Python批量替換文件內容,支持嵌套文件夾
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import os path = "./" for root,dirs,files in os.walk(path): for name in files: #print name if name.endswith( ".html" ): #print root,dirs,name filename = root + "/" + name f = open (filename, "r" ) filecontent = "" line = f.readline() while line: l = line.replace( ":/arcgis_js_api" , "/arcgisapi" ) filecontent = filecontent + l line = f.readline() f.close() f = file (filename, "w" ) f.writelines(filecontent) f.close() |
以上就是python創建文本文件的簡單方法的詳細內容,更多關于python怎么創建文本文件的資料請關注服務器之家其它相關文章!
原文鏈接:https://www.py.cn/jishu/jichu/19956.html