導航:首頁 > 編程語言 > python寫文件

python寫文件

發布時間:2022-01-24 15:20:47

python寫文件 寫不進去 也不報錯

你的寫模式錯誤。用w模式,每次會覆蓋原來的,所以,你只會得到最後寫入的東西,而你最後寫入了一個換行。想要追加寫入,用a模式

❷ python怎麼以追加的方式寫文件

一、用Python創建一個新文件,內容是從0到9的整數, 每個數字佔一行:

#python

>>>f=open('f.txt','w') # r只讀,w可寫,a追加

>>>for i in range(0,10):f.write(str(i)+' ')

. . .

>>> f.close()

二、文件內容追加,從0到9的10個隨機整數:

#python

>>>import random

>>>f=open('f.txt','a')

>>>for i in range(0,10):f.write(str(random.randint(0,9)))

. . .

>>>f.write(' ')

>>>f.close()

三、文件內容追加,從0到9的隨機整數, 10個數字一行,共10行:

#python

>>> import random

>>> f=open('f.txt','a')

>>> for i in range(0,10):

. . . for i in range(0,10):f.write(str(random.randint(0,9)))

. . . f.write(' ')

. . .

>>> f.close()

四、把標准輸出定向到文件:

#python

>>> import sys

>>> sys.stdout = open("stdout.txt", "w")

❸ python 寫入文件 只能寫入一行

ft=open("a",'w')
try:
ft.write(' '.join(result))
except:
log.error('writebackuperror:'+JOBNAME)
finally:
ft.close()
os.chdir(basePath)

❹ Python如何讀寫文本文件

1.open使用open打開文件後一定要記得調用文件對象的close()方法。比如可以用try/finally語句來確保最後能關閉文件。
file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
註:不能把open語句放在try塊里,因為當打開文件出現異常時,文件對象file_object無法執行close()方法。
2.讀文件讀文本文件input = open('data', 'r')
#第二個參數默認為r
input = open('data')

讀二進制文件input = open('data', 'rb')
讀取所有內容file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
讀固定位元組file_object = open('abinfile', 'rb')
try:
while True:
chunk = file_object.read(100)
if not chunk:
break
do_something_with(chunk)
finally:
file_object.close( )
讀每行list_of_all_the_lines = file_object.readlines( )
如果文件是文本文件,還可以直接遍歷文件對象獲取每行:
for line in file_object:
process line
3.寫文件寫文本文件output = open('data.txt', 'w')
寫二進制文件output = open('data.txt', 'wb')
追加寫文件output = open('data.txt', 'a')

output .write("\n都有是好人")

output .close( )

寫數據file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )

❺ python向文件內寫入數據

f=open("a.txt","w")
foriinrange(1,10):
f.write("<user> <id>"+str(i)+"</id> </user> ")
f.close()

因為i是int型,所以要先轉為str型,再進行字元串拼接,然後寫入文件

❻ python文件寫操作

這樣把
教你個簡單的辦法
python一般不會在原文件中操作的,一般會讀出來,操作,然後再寫入的。代碼如下:
#encoding:gbk
insert='123'
#你想插入的字元串
line=''
#最終文件內容
f=open("1.txt","r")
i=f.readline()
#讀取文件內容
f.close()
pre=i[0:3]
last=i[3:]
line=pre+insert+last
f=open("1.txt","w")
f.write(line)
f.close()

❼ 怎樣用python寫文件

這個應該打開之後有會有讓你讓你寫字的,然後你就可以把你想寫的寫上。

❽ python寫文件後文件中沒有

由於硬碟有緩沖機制,fwrite後數據並沒有實際寫入到磁碟,而是在緩沖區中,所以這時候打開文件看可能內容是空,需要調用fflush,這時候才能強制把數據寫入到文件中,或者調用fclose,文件關閉時數據也會寫入到文件中。

閱讀全文

與python寫文件相關的資料

熱點內容
什麼樣的app上買機票最便宜 瀏覽:985
安卓如何查看異常重啟 瀏覽:715
解壓音樂排名 瀏覽:383
安卓手機瀏覽器怎麼掃二維碼 瀏覽:715
通達信成本均線源碼 瀏覽:614
可以下載的解壓音頻 瀏覽:564
海賊王怎麼換伺服器 瀏覽:318
計算機上的共享文件夾映射 瀏覽:940
榮耀安裝包在文件夾哪裡 瀏覽:196
機票php源碼 瀏覽:233
linux共享mac 瀏覽:924
中國沒有國外的伺服器地址 瀏覽:759
為什麼退款伺服器連接錯誤 瀏覽:557
android簡訊存儲位置 瀏覽:972
unix網路編程卷4 瀏覽:808
找靚機app下單什麼時候發貨 瀏覽:413
android一個應用兩個進程 瀏覽:803
linux硬碟復制 瀏覽:808
php圖片伺服器搭建 瀏覽:801
下載壓縮文件怎麼打開 瀏覽:194