我需要从文件中加总数字

时间:2014-07-31 23:10:06

标签: python

我正在从文本文件中读取数字,其结构是每行两个数字。我需要打开这个文件,并从两者的范围中总结数字。我的程序完全按照我的要求进行,除非它达到负范围。因为我需要添加所有数字,所以我在范围的maxNumber末尾添加了+ 1。但是,例如,如果maxNum为负四,则它使得范围从-3而不是-5应该如此。我怎样才能解决这个问题?我也想知道将结果写入outPut文件的最佳方法。感谢

def numberSum1():
inFile = input('Please enter name of input file: ')
outFile = input('Please enter name of output file: ')

with open(inFile, 'r') as file1, open(outFile, 'w') as file2:
    finalList = []
    x = file1.readline()



    for x in file1:
        n, m = x.split()
        print(n,m)
        minNum = int(min(n,m))
        maxNum = int(max(n,m))
        print(minNum)
        print(maxNum)
        for w in range(minNum, maxNum + 1):
            finalList.append(w)

            finalContent = sum(finalList)
        print('Sum from {} to {} is {}'.format(minNum, maxNum, finalContent))
        finalList = []


file1.close()
file2.close()

1 个答案:

答案 0 :(得分:1)

问题在于您传递给minmax函数的参数。您需要将它们从strings转换为ints,然后再比较它们以查看哪个更大(现在,它错误地认为"-4"大于"-2")。试试这个:

for x in file1:
    n, m = [int(k) for k in x.split()]
    minNum = min(n,m)
    maxNum = max(n,m)