Dealing with files...

Alex Martelli aleax at aleax.it
Fri Apr 25 18:51:12 EDT 2003


lost wrote:

> Hi guys!
> I'm starting to deal with files, and need to know how to deal directly
> with the filesystem. what I'm looking for, is similar to this pseudo code:
> 
> for each_file in "/var/path/to/files/":
> print each_file #show the NAME of the file
> write the NAME of the file    into file_list.txt
> print "done"
> 
> This would print the name of each file in /var/path/to/files (for example,
> a list of html files), and then add the name of the file into
> file_list.txt.
> 
> Any help on this would be very much appreciated! Thanks.

import os

file_list = open('file_list.txt', 'a')

for each_file in os.dir('/var/path/to/files/'):
    print each_file
    file_list.write(each_file)
    file_list.write('\n')

file_list.close()

print 'done'


Here, I'm assuming you want to APPEND the names of the files,
one per line, to the textfile whose name you indicated.

Also, I'm assuming that you want to see subdirectories (if any)
as well as files.

It's trivially easy to make each of these assumptions in some
OTHER direction, of course, but, unless you give precise specs,
people who try to help you will have to just take their best
guesses at what you might have meant.


Alex





More information about the Python-list mailing list