Categories
Uncategorized

Simple File Lists – python

How to make quick directory lists in python.

All of these will use listdir in the os module.

so we need to import it first

from os import listdir

Now we want to list all the files in a directory called my_folder.

But the trick is that we only want the text files.

list_text_files = [x for x in listdir('my_folder') if x.endswith('.txt')]

Another thing we can do is to look for strings within the file name.

So we can search for all the files that contain ‘important’ on the file namte

list_important files = [x for x in listdir('my_folder') if 'important' in x]

Simple!

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s