2013-03-01 55 views
0

第一次執行此程序時,除了新行之外,生成的文件中沒有任何內容。但是第二次執行它時,它會正確寫入'out.txt',但第一次執行的新行仍然存在。爲什麼第一次不正常?寫入文件僅在第一次執行時給出新行

bhaarat = open('bhaarat.txt', 'r+') 
bhaarat_read = bhaarat.read() 

out = open('out.txt', 'r+') 
out_read = out.read() 

bhaarat_split = bhaarat_read.split() 

for word in bhaarat_split: 
    if word.startswith('S') or word.startswith('H'): 
     out.write(word + "\n") 

bhaarat.write('\n23. English\n') 
print out_read 
print bhaarat_read 

bhaarat.close() 
out.close() 
+0

您可以轉儲文件的內容以查看結構嗎? – Ketouem 2013-03-01 08:58:18

+0

我很抱歉,我很新,所以我不太清楚你的意思。你的意思是'貓文件'來看看它的內容? – lche 2013-03-01 09:08:54

回答

0

這是Windows的問題。解決方法(see python mailing list)是使用

f.seek(f.tell()) 
調用之間

read()write()上用的+一個選項打開的文件f

根據您的問題,您必須先撥bhaarat.seek(bhaarat.tell()),然後用bhaarat_read = bhaarat.read()讀取文件,然後再用bhaarat.write('\n23. English\n')寫入文件。你的out也一樣。

在Python3這個問題是固定的,所以更有理由切換:)


編輯 下面的代碼對我的作品。文件bhaarat.txtout.txt都必須存在。

bhaarat = open('bhaarat.txt', 'r+') 
bhaarat_read = bhaarat.read() 
bhaarat.seek(bhaarat.tell()) 
out = open('out.txt', 'r+') 
out_read = out.read() 
out.seek(out.tell()) 
bhaarat_split = bhaarat_read.split() 

for word in bhaarat_split: 
    if word.startswith('S') or word.startswith('H'): 
     out.write(word + "\n") 

bhaarat.write('\n23. English\n') 
print out_read 
print bhaarat_read 

bhaarat.close() 
out.close() 
+0

bhaarat.seek(f.tell())給了我一個錯誤,所以我嘗試了bhaarat.seek(bhaarat.tell())。我不確定這是否正確。 但是,我得到同樣的問題... – lche 2013-03-01 09:23:11

+0

@ user69498這是我的代碼中的錯誤:)你必須使用'bhaarat.seek(bhaarat.tell())''。對不起 – halex 2013-03-01 09:24:49

+0

@ user69498你是否也在你的代碼中加入了'out.seek(out.tell())'? – halex 2013-03-01 09:27:55

相關問題