Profile

Click to view full profile
Hi, I'm Veerapat Sriarunrungrueang, an expert in technology field, especially full stack web development and performance testing.This is my coding diary. I usually develop and keep code snippets or some tricks, and update to this diary when I have time. Nowadays, I've been giving counsel to many well-known firms in Thailand.
view more...

Saturday, November 6, 2010

How to list files in the directory in Python

Python can easily list files in the specific directory by using "dircache".

For example,

1. I have a folder "Test" under "C:\\", and this folder has 4 files contains 1.txt, 2.txt, 3.txt, 4.txt

2. Open the command at "C:\\" using "SHIFT + RIGHT CLICK"
more at => Windows: http://darkkung-blog.blogspot.com/2010/10/open-command-window-at-current-path-in.html
Linux-Ubuntu: http://darkkung-blog.blogspot.com/2010/10/quick-open-teminal-in-ubuntu-by-using.html

3. Type "python" to open Python Interactive Shell

4. Use the following code to see your files in that directory.

import dircache
flist = dircache.listdir("/Test/")
print flist

This technique can be used with "os.path" to check the contents in that directory which one is file or directory such as "os.path.isdir()", "os.path.isfile()".
more at => http://docs.python.org/library/os.path.html#os.path.islink


p.s. This technique is operating system independent.
Credit: http://www.programmersheaven.com/mb/python/191482/191482/list-files-in-a-directory/

No comments:

Post a Comment