Alex Rivera | Logout

Getting Every File in a Windows Directory

Asked 2011-04-12T00:59:20.977
30

I have a folder in Windows 7 which contains multiple .txt files. How would one get every file in said directory as a list?

Edit
Report

1 Answer

1

If you just need the current directory, use os.listdir.

>>> os.listdir('.') # get the files/directories
>>> [os.path.abspath(x) for x in os.listdir('.')] # gets the absolute paths
>>> [x for x in os.listdir('.') if os.path.isfile(x)] # only files
>>> [x for x in os.listdir('.') if x.endswith('.txt')] # files ending in .txt only

You can also use os.walk if you need to recursively get the contents of a directory. Refer to the python documentation for os.walk.

answered 2011-04-12T01:08:40.900

Your Answer