簡體   English   中英

寫入文件僅在第一次執行時換行

[英]Writing to file gives only new line on first execution

第一次執行該程序時,除換行外,生成的文件中沒有任何內容。 但是第二次執行它時,它正確地寫入了“ 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()

這是Windows的問題。 解決方法( 請參閱python郵件列表 )是要使用的

f.seek(f.tell())

在使用+選項之一打開的文件f上對read()write()調用之間。

適應您的問題后,您必須先使用bhaarat_read = bhaarat.read()讀取文件,然后再使用bhaarat.write('\\n23. English\\n')對其進行寫入,然后調用bhaarat.seek(bhaarat.tell()) 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM