无法在python 2.7中获取文本文件输出

无法在python 2.7中获取文本文件输出,python,python-2.7,output,Python,Python 2.7,Output,我从Numbers.txt文件中获取了输入,并想在out.txt文件中写入输出, 谁能告诉我哪里出了问题 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

我从Numbers.txt文件中获取了输入,并想在out.txt文件中写入输出, 谁能告诉我哪里出了问题

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()

以下是代码的改进版本:

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));

您需要缩进
out\u file.write()
,否则您只会写最后一行您没有写的
text.close()
,请看一看示例:这使编写代码更容易消除错误。我也不会在Actual.BTW中导入一些东西,通常应该在脚本的顶部放置<代码>导入< /COD>语句,而不是在中间的某个地方埋葬,特别是不在一个循环内。您的
import
是否处于循环中并不重要,因为Python足够聪明,只需导入一次模块,但它看起来仍然很混乱是无用的。而且不需要用分号终止Python语句。另外,不要将文件写入Python安装!!!嗨,我是一个刚开始学习的初学者。感谢您提供了改进的代码,但输出未处理。这与提供的输入相同,我希望我们必须附加已处理的部分并添加到fout。是的,您的代码基本上是从输入文件中提取一行,将数字发送到卡,并将该行复制到输出文件。
x
是您处理过的数据吗?是的,x是处理过的数据。martijnn2008即使open默认为'r',我认为如果指定了它会更清晰,特别是如果OP开始编码。此外,为了清晰起见,即使有额外的缩进,我也会使用两行。那么在输出文件中,您只需要经过处理的数据,还是两者都需要?如果两者都是,您应该指定它们是如何组合在一起的:连接的,不同的行?