2016-04-27 68 views
1

使用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

在打開文件之前,您沒有關閉文件。數據只有在關閉後纔會刷新到文件中。

再次嘗試打開它之前關閉該文件: -

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

或者你可以使用一個更加有選項可以打開這樣的文件是關閉是照顧的文件...

0

由於在再次打開文件之前,您沒有關閉文件,您沒有看到新的數據。你應該做的是在打開文件進行寫入時使用另一個語句,以便正確關閉文件。