Printing File Names In Folder Using Python

Daily post #4 – Today I’m going to share how you can use Python code to fetch file names inside a specified directory.

import os

indir = '/users/omkarbhagat/desktop/batman/'
for root, dirs, filenames in os.walk(indir):
	for x in filenames:
		x = "/users/omkarbhagat/desktop/batman/"+x
		print(x)

Note that the python code above only works with correct indentation so if something breaks, make sure to have correct indentation. Also make sure to have all spaces or all tabs in the code, don’t mix them up!

I had the following setup – A folder called batman on my desktop with couple of txt files inside it. Running the above code returns the following result –

Omkars-MacBook-Pro-3:desktop omkarbhagat$ python test.py
/users/omkarbhagat/desktop/batman/batman-begins.txt
/users/omkarbhagat/desktop/batman/bvs.txt
/users/omkarbhagat/desktop/batman/tdk.txt
/users/omkarbhagat/desktop/batman/tdkr.txt

Once I have a file name or directory in a variable, I can do stuff with it. For example, I can change all file names, or edit the content of all these files by a conditional statement or something. I’ll probably share that in a separate post. That’s all for today, thanks for reading! đŸ™‚