ファイルにデータを開いたり書き込んだりするときのPythonの動作について質問があります。 私は何時間も実行できるように構築された大規模なコードを持っており、ASCIIファイルにテキストを書き込む必要があります。コードはwith open
メソッドを使用し、プログラムの実行中にファイルを開いたままにします。 場合によっては、プログラムの実行を停止して、終了ステータスがProcess finished with exit code -1
になることがあります。ファイルへの書き込み中に不思議な動作
コードが実行されていて、ASCIIファイルにテキストが書き込まれているという確認が表示されますが、コードを停止するとファイルが空になります。
import time
# Create the .txt files
with open('D:/Stuff/test1.txt', 'w') as write1:
pass
with open('D:/Stuff/test2.txt', 'w') as write2:
pass
# Write some text into the.txt files
# Case 1. The code runs until the end
with open ('D:/Stuff/test1.txt', 'a') as infile1:
a = range(1, 50, 1)
infile1.write(str(a))
print "Writing completed!"
# Case 2. I stop the execution manually. I use time.sleep to be able to stop it in this example
with open ('D:/Stuff/test2.txt', 'a') as infile2:
b = range(1, 50, 1)
infile2.write(str(b))
print "Writing completed!"
print "Start sleep"
time.sleep(10)
<< At this line I end the script manually>>
print "End sleep"
何が起こることは、ケース1は、テキストがファイルに書き込まれますが、ケース2には、私は彼らが空を得ることです: 以下のコード、のは、例えばましょう。 なぜこれが起こっているのですか?どのように解決できますか?
関連はありませんが、最初の数行は 'w'で始まる必要はありません。 'a'はファイルが存在しない場合に作成する – Wboy
私はそれを知らなかった。ありがとう! :) – Litwos
自動的に行う*でフラッシュをバイパスするために、指定された位置でスクリプトをどのように終了させましたか? – guidot