0

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

1
  • You really should start the tags with the language you are using. What is it again? Commented Jul 13, 2012 at 17:11

3 Answers 3

3

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() 
Sign up to request clarification or add additional context in comments.

1 Comment

yeah i have first done the same mistake you wrote on the above. thank you for your advice. it really helped
2

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.

Comments

2

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) 

2 Comments

i didn't know about with(). thank you i'll try this one later
@user1512491 I'll suggest you to learn with instead of manually closing files, read more about it here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.