craigbdill
craigbdill

Reputation: 11

Why can't I read file after my for loops python using ubuntu

For some reason after my for loops I am not able to read the ouput text file. For example :

for line in a:
 name = (x)
 f = open('name','w')
for line in b:
 get = (something)
 f.write(get)
for line in c:
 get2 = (something2)
 f.write(get2)

 (the below works if the above is commented out only)

f1 = open(name, 'r')
for line in f1:
 print line

If I comment out the loops, I am able to read the file and print the contents.

I am very new to coding and guessing this is something obvious that I am missing.However I can't seem to figure it out. I have used google but the more I read the more I feel I am missing something. Any advice is appreciated.

Upvotes: 1

Views: 144

Answers (1)

Danica
Danica

Reputation: 28856

@bernie is right in his comment above. The problem is that when you do open(..., 'w'), the file is rewritten to be blank, but Python/the OS doesn't actually write out the things you write to disk until its buffer is filled up or you call close(). (This delay helps speed things up, because writing to disk is slow.) You can also call flush() to force this without closing the file.

The with statement bernie referred to would look like this:

 with open('name', 'w') as f:
     for line in b:
         b.write(...)
     for line in c:
         b.write(...)
 # f is closed now that we're leaving the with block
 # and any writes are actually written out to the file

 with open('name', 'r') as f:
     for line in f:
         print line

If you're using Python 2.5 rather than 2.6 or 2.7, you'll have to do from __future__ import with_statement at the top of your file.

Upvotes: 3

Related Questions