2017-02-28 30 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是处理数据。 –

相关问题