【问题标题】:Unable to get text file output in python 2.7无法在 python 2.7 中获取文本文件输出
【发布时间】:2017-02-28 10:04:10
【问题描述】:

我已从 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()

【问题讨论】:

  • 你需要缩进out_file.write()否则你只会写最后一行
  • 你没有做text.close(),看看这个例子:stackoverflow.com/questions/4617034/…,它可以更容易地编写无错误的代码。我也不会在 for 循环中导入一些东西。
  • 顺便说一句,您通常应该将import 语句放在脚本的顶部,而不是埋在中间的某个地方,尤其是不要放在循环中。你的 import 是否在循环中并不重要,因为 Python 足够聪明,只导入一次模块,但它看起来仍然很乱。
  • 另外,x=""; 没用。并且没有必要用分号终止 Python 语句。
  • 另外,不要将文件写入python安装!!!

标签: python python-2.7 output


【解决方案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));

【讨论】:

  • 您好,我是刚开始学习的初学者。感谢您提供改进的代码,但未处理输出,它与提供的输入相同,我希望我们必须附加处理过的部分并添加到 fout 中。
  • 是的,您的代码基本上是从输入文件中取出一行,将数字发送到卡并将该行复制到输出文件。 x 是您处理过的数据吗?
  • 是 x 是处理过的数据。
  • martijnn2008 即使 open 默认为 'r' 我认为如果指定它会更清楚,特别是如果 OP 开始编码。即使为了清晰起见,我也会使用两行缩进。
  • 那么在输出文件中您只需要处理过的数据,还是两者都需要?如果是两者,您应该指定它们的组合方式:连接,不同的行?
猜你喜欢
  • 2015-09-09
  • 1970-01-01
  • 1970-01-01
  • 2018-10-01
  • 2022-11-17
  • 2019-03-17
  • 1970-01-01
  • 2017-12-30
  • 1970-01-01
相关资源
最近更新 更多