【发布时间】:2018-03-16 18:45:36
【问题描述】:
我是 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 。你不能用
writelines吗? tutorialspoint.com/python/file_writelines.htm -
哈哈,是的,我现在知道了@Jay
标签: python python-3.x file-handling sentiment-analysis