0

I've run this code but it only writes in the text file the first directory in /home

for item in os.listdir('/home'): text_file_1 = open('/tmp/home_dir.txt', 'wb') text_file_1.write('%s\n' % item) text_file_1.close() 
2
  • Well you close the file after you write one line. Commented Feb 25, 2014 at 18:13
  • it should actually write the last one. Commented Feb 25, 2014 at 18:29

2 Answers 2

2

You should open the file outside the loop. Otherwise you "start over" every time you open it

Context managers (with statement) are the preferred way to open files

with open('/tmp/home_dir.txt', 'w') as text_file_1: for item in os.listdir('/home'): text_file_1.write('%s\n' % item) 
Sign up to request clarification or add additional context in comments.

7 Comments

or, text_file_1.writelines(fname + '\n' for fname in os.listdir('/home'))
That will certainly work as well, but I think this is clearer for beginners
So which one do you recommend?
@mgilson's answer is shorter, and mine is clearer. Whichever you feel comfortable with. Functionally they're nearly identical.
@mhlester -- Gotta learn comprehensions sometime. No better time than right now... :-)
|
0

I think you'll find it's the last item from os.listdir().

try this:

text_file_1 = open('/tmp/home_dir.txt', 'w') for item in os.listdir('/home'): text_file_1.write('%s\n' % item) text_file_1.close() 

Or this:

for item in os.listdir('/home'): text_file_1 = open('/tmp/home_dir.txt', 'a') text_file_1.write('%s\n' % item) text_file_1.close() 

When you open the new file handle and write to the file with 'w', it completely overwrites what was originally in it.

'a' allows you to append to the file.

I would recommend my first solution; opening and closing files is costly. If you're going to rapidly loop over items to write to a file you may as well keep it open.

Comments