0

I'm writing a program that has a function that writes to a file. Then a different function reads from the file prints the values then the min, max and avg values. When I try to read from the file I get the following error.

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

As far as I know this means that the variable getting passed to min is empty? I can't really understand why or how I should go about fixing it. Here is the rest of my code.

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()
rdend
  • 3
  • 3

3 Answers3

1

You have iterated on file two times so the list data is empty.

def read_output(file_name):
    f = open('file_name.txt')
    data = [float(line.rstrip()) for line in f]
    biggest = min(data)
    smallest = max(data)
    print("Biggest: {}".format(biggest))
    print("Smallest: {}".format(smallest))
    print("Average: {}".format(sum(data)/len(data)))

Best way to read and write to a file in python:

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')

There is also an error in write_output, when enter is pressed you must not write a newline because it is parsed when you read the file raising error:

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)
Andrea
  • 583
  • 5
  • 15
1

First, to write your file:

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)))

Then to read that file back line-by-line and calculate the min, max, and average:

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) 

Prints:

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

If the file is small enough, you can do this by reading the entire file into memory and using Python built-ins:

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))
dawg
  • 98,345
  • 23
  • 131
  • 206
0

Try reading and working with the data like this:

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

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

This one-line code should also work:

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

Edit: For some reference on efficient ways of reading lines I'd recommend checking this question out.

Community
  • 1
  • 1
Vinícius Figueiredo
  • 6,300
  • 3
  • 25
  • 44