2

我正在尝试制作一个程序,该程序从文件中获取数字列表(可能会改变行数和大小),然后打印出所有数字的总和和平均值。当我有一定数量的 linereads 时,我这样做没有问题,但是当 lineread 每次运行都会改变时,我对“正确”的方式感到困惑。

这是我正在进行的代码。我阅读了一下并找到了正确的(?)循环文件以查找长度的方法,但不确定如何实现它,因为它当前会引发某种类型的 IO 错误。谢谢您的帮助!

def main():
    filename = input("Enter file name (name.txt):")
    try:
        file = open(filename, "r")
    except IOError:
        print("Error opening file!")

    totalLines = totalLineGet(filename)

    results = []
    for x in range(totalLines):
            results.append(getLineNumber(x+1, file))

    print("Total = ", numTotal)
    print("Average = ", numAvg)

def totalLineGet(_filename):
    count = 0
    _file = open(_filename, "r")
    for x in open(_file):
        count+= 1
    return count

def getLineNumber(linetoget, _file):
    try:
        intNumber = int(number = _file.readline())
    except ValueError:
        print("Error in file data!")

    return intNumber

main()
4

4 回答 4

2

我不确定你想做什么......但你应该能够一口气得到答案。enumerate()如果您需要知道项目/行号计数,您可以使用对可迭代对象(在本例中为文件)进行编号。

假设每行有一个 int():

with open(filename, "r") as in_f:
    numbers = []
    for line in in_f: 
        line = line.strip() # remove whitespace
        if line: # make sure there is something there
            number_on_line = int(line) 
            numbers.append(number_on_line)
    sum_of_numbers = sum(numbers)
    avg_of_numbers = sum(numbers)/len(numbers)

如果这是您应该使用该csv模块查看的 CSV 数据,它会为您将行/列拆分为行/列。

import csv
filename = "somefile"
with open(filename, "rb") as in_f: # <-- notice "rb" is used
    reader = csv.reader(in_f)
    for row in reader:
        for col in row:
            # do stuff
            ...
于 2012-11-30T02:21:05.670 回答
1

一个简单的解决方案,做你想做的......

filename = 'tmp.txt'
f = open(filename)
s, totnum = 0, 0
for line_number, line in enumerate(f):
    nums = map(int, line.split())
    s += sum(nums)
    totnum += len(nums)

print "numbers:", totnum, "average:", 1.0*s/totnum
于 2012-11-30T02:27:30.373 回答
1

这假设您的文件每行只有数字而不是字符,否则您将得到一个TypeError.

list_of_numbers = []

with open('somefile.txt') as f:
   for line in f:
      if line.strip(): # this skips blank lines
          list_of_numbers.append(int(line.strip()))

print 'Total ',len(list_of_numbers)
print 'Average ',1.0*sum(list_of_numbers)/len(list_of_numbers)
于 2012-11-30T02:45:48.387 回答
1

关于如何做你想做的事,有一些很好的答案。至于 IO 错误,内置的 input() 尝试评估用户的输入,这既危险又不是您想要的。

尝试使用 raw_input() 内置。这会将用户的输入作为字符串返回。为了好玩,尝试运行您的脚本并将其__name__作为文件名,看看会发生什么。

于 2012-11-30T02:48:13.297 回答