H.Choi
H.Choi

Reputation: 3223

i'm using write() to write the results into a file but it does not contain the result of last loop

briefly, i have a code like:

for a in range(3):
 result = 'abcd' + a
 opener = open('file.txt', "a")
 print results
 opener.write(results)

my problem is, if i run this code in shell, i can see the printed results,

abcd0
abcd1
abcd2

but the file contains only,

abcd0abcd1

the output i want is,

abcd0abcd1abcd2

any suggestions? i can't find what's wrong with this code...

any help would be really great. thanks in advance

Upvotes: 0

Views: 112

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250931

use with(), so you don't have to worry about opening and closing of file, with() automatically closes the file as soon as program moves out of with block.

with open('data.txt','a') as opener:
    for a in range(3):
        results = 'abcd' + str(a)
        print results
        opener.write(results)

Upvotes: 2

fvu
fvu

Reputation: 32953

Ashwini Chaudhary's solution is a lot better, consider my answer just as a backgrounder on what went wrong and why it went wrong, and the difference between opening/closing files inside or outside the loop.

File opens and closes should be paired, like here, the file is repeatedly opened, written and closed inside the loop:

for a in range(3):
    result = 'abcd' + a
    opener = open('file.txt', "a")
    print results
    opener.write(results)
    opener.close()

However, in many cases it's not a good idea to open and close files inside a loop due to the cost of opening and closing a file, so it may be better to open the file before the loop, write the file in the loop, and close it after the loop:

opener = open('file.txt', "a")
for a in range(3):
    result = 'abcd' + a
    print results
    opener.write(results)
opener.close()

Of course, when the file remains open, and the loop is lengthy, you risk losing data should the program crash, be interrupted or on a reboot of the computer. In these cases, forcing a flush to the operating system is in many cases a better alternative than repeatedly opening/closing the file:

opener = open('file.txt', "a")
for a in range(3):
    result = 'abcd' + a
    print results
    opener.write(results)
    opener.flush()
opener.close() 

Upvotes: 3

hkothari
hkothari

Reputation: 254

you may want to try closing the file after you're done writing to it. if python quits before the file closes the last write might not get flushed and hence not written to the file. Just try adding:

opener.close()

To the end.

Upvotes: 2

Related Questions