【问题标题】:Unable to get sum to print in outfile无法在输出文件中打印总和
【发布时间】:2017-06-03 00:28:48
【问题描述】:

我正在尝试创建一个程序,该程序将对单独列表中的相应值求和,并使用计算的总和编写一个新文件。例如,我有 infile_1.txt 有 10 个项目,infile_2.txt 也有 10 个项目。目标是从infile_1.txt 中获取第一个数字,将其添加到infile_2 的第一个数字中,并使用两个数字的总和创建一个新的文本文件。这两个文件与我的程序位于同一个文件夹中,因此 Python 可以识别它们并将新文件也打印到该文件夹​​中。我使用的代码如下:

def sumen():
outfile = input("Name the output file: ")
myfile_1 = open("infile_1.txt",'r')
myfile_2 = open("infile_2.txt",'r')
outputfile = open(outfile, 'w')
for line in myfile_1:
    readfile1 = myfile_1.readline()
    readfile2 = myfile_2.readline()
    totalenergy = myfile_1[0:] + myfile_2[0:]
    print(totalenergy,file=outputfile)
myfile_1.close()
myfile_2.close()
outputfile.close()
sumen()

当我运行程序时,它允许我选择输出文件 (totalenergy.txt),然后它就结束了。我检查了 Python 创建的文件,里面没有任何内容。

目前,我遇到错误“totalenergy = myfile_1[0:] + myfile_2[0:] TypeError: '_io.TextIOWrapper' object is not subscriptable"。我还遇到了一个属性错误,这与关闭 infile 和 outfile 说“'str'没有属性有关'关闭' "

另外一个问题:如果两个文件的长度不同,是否可以重写 for 循环来解释长度的不同?我想知道的另一件事是totalenergy = myfile_1[0:] + myfile_2[0:] 行是否正确,因为 Python 在每次连续迭代期间抓取每个列表中的下一个值。

我在 python 方面相对较新,所以任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: python file loops sum output


    【解决方案1】:

    当你执行for line in myfile_1: 时,它会读取文件,所以myfile_1.readline() 会得到下一个 行。您不需要第二个语句。

    另外,readfile1readfile2 将是字符串。如果要将它们添加为整数,则需要调用int()进行转换。

    for readfile1 in myfile_1:
        readfile2 = myfile_2.readline()
        totalenergy = int(readfile1) + int(readfile2)
        print(totalenergy,file=outputfile)
    

    请参阅How to cleanly loop over two files in parallel in Python 了解编写此循环的其他方法。

    【讨论】:

    • 另请注意,根据 Python 版本,混合迭代和显式调用 .readline() 并不安全,不一定能正常工作。只需迭代(通过循环隐式或通过next(myfile_1) 显式),不要同时调用.readline()
    • @ShadowRanger 当它们是不同的文件时真的不安全吗?
    • 啊,错过了这是两个不同的文件,这很安全。当然,for readfile1, readfile2 in zip(myfile_1, myfile_2): 无论如何都会更直接地完成并行迭代。
    • @ShadowRanger 混合迭代和 readline 是他原始代码中的问题。我链接到的问题中的一个答案显示了如何使用zip()izip()
    • @Barmar 非常感谢您的快速响应!我在进行调整后测试了代码,它工作了
    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 2011-12-19
    • 2018-07-28
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    相关资源
    最近更新 更多