python 3.5没有打印输出到屏幕

时间:2016-04-27 12:48:16

标签: printing python-3.5

使用Python 3.5我创建了代码来处理文件并将输出写入另一个文件。以下是相关代码;

with open('2016_01_22_Investor_Companies_stops.txt','r') as stops_Investor_Companies:
    stops_Investor_Companies = stops_Investor_Companies.read()
    stops_Investor_Companies = nltk.word_tokenize(stops_Investor_Companies)
    stops_Investor_Companies= [w.lower() for w in stops_Investor_Companies]
    stops_Investor_Companies = str(stops_Investor_Companies)
    outfile = open ('stops_Investor_Companies_cln.txt', 'w')
    outfile.write(stops_Investor_Companies)
print ('1. Investor Companies')
print (' ')
with open('stops_Investor_Companies_cln.txt','r') as fin:
    print(fin.read())
print (' ')

结果是文本1. Investor Companies打印到屏幕,但文件stops_Investor_Companies_cln.txt未打印到屏幕上。

但是,我可以使用相同的代码段作为单独的脚本将文件stops_Investor_Companies_cln.txt打印到屏幕上;

with open('stops_Investor_Companies_cln.txt','r') as fin:
    print(fin.read())

2 个答案:

答案 0 :(得分:2)

在再次打开文件之前,您没有关闭该文件。只有在关闭数据后才能在文件中刷新数据。

在再次打开文件之前尝试关闭文件: -

outfile = open ('stops_Investor_Companies_cln.txt', 'w')
outfile.write(stops_Investor_Companies)
outfile.close()

或者您可以再使用一个选项打开文件,以便关闭文件...

答案 1 :(得分:0)

由于在再次打开文件之前尚未关闭文件,因此您无法看到新数据。当你打开文件进行写作时,你应该做的是使用另一个with语句,以便正确关闭。

相关问题