我是 python 3 的新手,正在研究推文的情感分析。我的代码以一个 for 循环开始,该循环接收 50 条推文,我对这些推文进行了清理和预处理。之后(仍在 for 循环内)我想将每条推文保存在一个文本文件中(每条推文都在一个新行上) 代码如下:
for loop:
..
print statments
..
if loop:
filename=open("withnouns.txt","a")
sys.stdout = filename
print(new_words)#tokenised tweet that i want to save in txt file
print("\n")
sys.stdout.close()#i close it because i dont want to save print statements OUTSIDE if loop to be saved in txt file
..
..
print statements
运行后显示错误:第 71 行关闭文件上的 I/O 操作(if 循环后的第一个打印语句)
我的问题是,有什么方法可以暂时关闭然后打开 sys.stdout
并使其仅在 if 循环内处于事件状态?
最佳答案
您根本不需要分配给 sys.stdout
。只需告诉 print()
使用 file
参数写入文件即可:
print(new_words, file=filename)
print("\n", file=filename)
现在不需要为 sys.stdout
分配任何内容,因为现在 print()
会直接写入您的文件。
您还想使用文件对象作为上下文管理器,因此它已关闭,或者您:
with open("withnouns.txt","a") as filename:
print(new_words, file=filename)
print("\n", file=filename)
无论如何,您都不需要关闭 sys.stdout
引用,而是想关闭 filename
,并将 sys.stdout
恢复为它的状态以前的状态。
如果您确实需要替换 sys.stdout
,您有几个选项,从最正确到最不正确:
使用
contextlib.redirect_stdout()
:import contextlib with contextlib.redirect_stdout(some_fileobject): # do things that write to stdout
在 block 的末尾,
stdout
已为您修复。首先手动存储
sys.stdout
:old_stdout = sys.stdout sys.stdout = new_object try: # do things that write to stdout finally: sys.stdout = old_stdout
使用
sys.__stdout__
copy ;这是在启动时设置的:sys.stdout = new_object try: # do things that write to stdout finally: sys.stdout = sys.__stdout__
您需要考虑到在代码运行之前
sys.stdout
可能已被其他内容替换,并将其恢复为sys.__stdout__
可能是做错事了。
关于python - 如何在嵌套循环中关闭 sys.stdout ,以便它不会将打印语句复制到文件中的内循环之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49327630/