[英]While loop to write in several text files
我正在嘗試在不同的文本文件中編寫一些文本行。
問題是我無法關閉第一個並使用 while 循環移動到下一個。
我想使用 while 循環,因為我要創建的文件數量是未定義的,所以在每個案例結束時,我希望程序詢問我是否已經完成工作,如下所示:
status = input('finished? ')
如果答案是肯定的,我希望程序停止。 如果答案是否定的,我希望程序繼續創建 .txt 文件並打印我指定的信息。
import sys
while True:
file_txt = str(input('.txt file name? ')+'.txt')
sys.stdout = open(file_txt, "w")
print('This will be printed in the file')
sys.stdout.close()
status = input('finished? ')
if status == 'yes':
break
else:
continue
這段代碼的問題是我收到以下錯誤:
ValueError: I/O operation on closed file.
不清楚為什么需要sys
模塊。 只需寫入文件 object
具體來說,關閉系統 stream 將其永久關閉
while True:
file_txt = input('.txt file name? ')+'.txt'
with open(file_txt, "w") as f:
f.write('This will be printed in the file')
status = input('finished? ')
if status == 'yes':
break
猜猜input('finished? ')
在哪里寫文本? 在你剛剛關閉的sys.stdout
中! 嘗試將其設置回控制台
sys.stdout = open(file_txt, "w")
print('This will be printed in the file')
sys.stdout.close()
sys.stdout = sys.__stdout__
首先,除非循環底部有更多代碼,否則沒有必要continue
。
您正在嘗試使用print
寫入sys.stdout
(標准輸出)。 關閉sys.stdout
后,您將其重置。 但是,當我運行您的代碼(來自 unix)時,當您在標准輸出中輸入任何內容時, input
似乎訪問標准stdout
- 即使您沒有輸入任何內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.