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() 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() 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) text_file_1.writelines(fname + '\n' for fname in os.listdir('/home'))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.