2017-02-28 49 views
0

我已輸入從Numbers.txt文件,並希望寫out.txt文件輸出, 任何人都可以引導什麼錯誤。無法獲取文本文件輸出在Python 2.7

import num2word_EN as s 
text = open("C:\\Users\\eanaaks\\Desktop\\Python Practice Program\\Numbers.txt","r") 
outfile = open("C:\\Users\\eanaaks\\Desktop\\Python Practice Program\\out.txt", "w") 
for line in text: 
    line = line.rstrip() 
    num = int(line) 
    print line 
    x = s.to_card(num) 
    print (x) 
outfile.write("%s\n"%(line)); 
outfile.close() 
text.close() 
+0

請問你的文件是什麼樣子? –

+5

你需要縮進'out_file.write()'否則你會只寫最後一行 –

+2

你沒有做'text.close()',看看這個例子:http://stackoverflow.com/問題/ 4617034/how-can-i-open-multiple-files-using-open-in-python這使得它更容易編寫錯誤免費。我也不會在for循環中導入某些東西。 – martijnn2008

回答

1

這裏是你的代碼的改進版本:

import num2word_EN as s 

input_file = 'C:\Users\eanaaks\Desktop\Python Practice Program\Numbers.txt' 
output_file = 'C:\Users\eanaaks\Desktop\Python Practice Program\out.txt' 

with open(input_file, 'r') as fin 
    with open(output_file, 'w') as fout: 
     for line in fin: 
      num = int(line) 
      print(line) 
      x = s.to_card(num) 
      print(x) 
      # What's the data type of x? int? string? 
      # This will write the original data and the processed data separated by tab. 
      fout.write('%s\t%s\n' % (line.rstrip(), x)); 
+0

嗨,我是剛開始學習的初學者。感謝您提供了改進的代碼,但輸出不被處理,它與提供的輸入相同,我希望我們必須追加處理的部分並添加到fout中。 –

+0

是的,您的代碼基本上是從輸入文件中取出一行,將該數字發送到卡並將該行復制到輸出文件。 'x'是你的處理數據嗎? –

+0

是x是處理數據。 –