[英]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.