从文件读取并提供最小值,最大值和平均值的程序

时间:2017-05-08 01:07:48

标签: python

我正在编写一个具有写入文件功能的程序。然后从文件读取不同的函数打印值,然后打印min,max和avg值。当我尝试从文件中读取时,我收到以下错误。

Traceback (most recent call last):                                                                                                                                       
  File "A8.py", line 39, in <module>                                                                                                                                     
    main()                                                                                                                                                               
  File "A8.py", line 35, in main                                                                                                                                         
    read_output('file_name.txt')                                                                                                                                         
  File "A8.py", line 19, in read_output                                                                                                                                  
    biggest = min(data)                                                                                                                                                  
ValueError: min() arg is an empty sequence

据我所知,这意味着传递给min的变量是空的?我无法理解为什么或如何修复它。这是我的其余代码。

def write_input(file_name):
    try:
        inputfile = open('file_name.txt','w')
        while True:
            inp = raw_input("Please enter a number. Press Enter to exit")
            inputfile.write(str(inp) + '\n')
            if inp == "":
                inp = "\n"
                break
    except Exception as err:
        print(err)

def read_output(file_name):
    f = open('file_name.txt')
    for line in iter(f):
        print line

    data = [float(line.rstrip()) for line in f]
    biggest = min(data)
    smallest = max(data)
    print("Biggest" + biggest)
    print(smallest)
    print(sum(data)/len(data))


def main():
    print(" 1. Save data (which runs write_input)")
    print(" 2. Get stats (which runs read_output)")
    print(" 3. Quit")   
    x = raw_input("Please select an option")

    if x == '1':
        write_input('file_name.txt')
    if x == '2':
        read_output('file_name.txt')
    if x == '3':
        print("Goodbye")

main()

3 个答案:

答案 0 :(得分:1)

您已经对文件进行了两次迭代,因此列表数据为空。

with open('file_name.txt', 'r') as my_file:
    for line in my_file:
        print line


with open('file_name.txt', 'w') as my_file:
    my_file.write('ciao')

在python中读取和写入文件的最佳方法:

def write_input(file_name):
    try:
        inputfile = open('file_name.txt','w')
        while True:
            inp = raw_input("Please enter a number. Press Enter to exit")
            if inp == "":
                break
            inputfile.write(str(inp) + '\n')
    except Exception as err:
        print(err)

write_output中也有一个错误,当按下enter时你不能写一个换行符,因为当你读取文件引发错误时它会被解析:

docker run --name dev-cassandra -d cassandra:latest

答案 1 :(得分:1)

首先,写一下你的文件:

from random import randint
with open('/tmp/file', 'w') as f_out:
    for n in range(100000):
        f_out.write('{}\n'.format(randint(0,1000000)))

然后逐行读取该文件并计算最小值,最大值和平均值:

import sys 
m_max=-sys.maxint
m_min=sys.maxint
m_sum=0      
with open('/tmp/file') as f_in:
    for cnt, line in enumerate(f_in, 1):
        n=int(line)
        m_max=n if n>m_max else m_max
        m_min=n if n<m_min else m_min
        m_sum+=n

print 'max: {}\nmin: {}\navg: {}\ncnt: {}'.format(m_max, m_min, m_sum/cnt, cnt) 

打印:

max: 1000000
min: 5
avg: 499425.96042
cnt: 100000

如果文件足够小,可以通过将整个文件读入内存并使用Python内置函数来实现:

with open('/tmp/file') as f_in:
    nums=[int(line) for line in f_in]
    print 'max: {}\nmin: {}\navg: {}\ncnt: {}'.format(max(nums), min(nums), 
                       float(sum(nums))/len(nums), len(nums))

答案 2 :(得分:0)

尝试阅读和使用这样的数据:

with open("test.txt") as f:
    content = f.readlines()

data = [float(line.strip()) for line in content]

这个单行代码也应该有效:

data = [float(line.strip()) for line in open("test.txt")]

编辑:有关阅读行的有效方法的一些参考,我建议您检查this question out.