mko
mko

Reputation: 22114

Why I can't read anything with File.open in python when I open the file to write first?

f = open('day_temps.txt','w')
f.write("10.3,10.1,9.9,9.9,9.8,9.6,9.0,10.1,10.2,11.1")
f.close

def get_stats(file_name):
    temp_file = open(file_name,'r')
    temp_array = temp_file.read().split(',')
    number_array = []
    for value in temp_array:
        number_array.append(float(value))
    number_array.sort()
    max_value = number_array[-1]
    min_value = number_array[0]
    sum_value = 0
    for value in number_array:
        sum_value += value
    avg_value = sum_value / len(number_array)
    return min_value, max_value, avg_value

mini, maxi, mean = get_stats('day_temps.txt')
print "({0:.5}, {1:.5}, {2:.5})".format(mini, maxi, mean)

without the first 3 line, the code works, with it I can't read nothing in the temp_file, I don't get it, any idea?

Upvotes: 2

Views: 3302

Answers (3)

whatnick
whatnick

Reputation: 5480

f.close is just invoking the method object for printing rather than calling the method.In the REPL you get this:

f.close
<built-in method close of file object at 0x00000000027B1ED0>

Add your method call brackets.

Upvotes: 1

Blender
Blender

Reputation: 298532

You never closed the file with this line of code:

f.close

Either use f.close(), or the with syntax, which auto-closes the file handle and prevents problems like this:

with open('day_temps.txt', 'w') as handle:
    handle.write("10.3,10.1,9.9,9.9,9.8,9.6,9.0,10.1,10.2,11.1")

Also, you can condense your code significantly:

with open('day_temps.txt', 'w') as handle:
    handle.write("10.3,10.1,9.9,9.9,9.8,9.6,9.0,10.1,10.2,11.1")

def get_stats(file_name):
    with open(file_name, 'r') as handle:
        numbers = map(float, handle.read().split(','))

    return min(numbers), max(numbers), sum(numbers) / len(numbers)

if __name__ == '__main__':
    stats = get_stats('day_temps.txt')
    print "({0:.5}, {1:.5}, {2:.5})".format(*stats)

Upvotes: 6

abought
abought

Reputation: 2680

In line 3, f.close should read f.close(). To force the file to write immediately (rather than when the file is closed), you can call f.flush() after writing: see Why file writing does not happen when it is suppose to happen in the program flow? for more details.

Alternately, the file will close naturally when the script is completely ended (including the closing of any interactive interpreter windows, like IDLE). In some cases, forgetting to properly flush or close a file can lead to extremely confusing behavior, such as bugs in interactive sessions that would not be seen if running the script from the command line.

Upvotes: 3

Related Questions