faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

21 of 22 people (95%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

Getting files in directory (was: Directories)

Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 353, Andrew M. Kuchling


"""
Packages: operating_systems.generic
"""
"""
From:           	"Andrew M. Kuchling" <akuchlin@cnri.reston.va.us>
Date sent:      	Tue, 27 Apr 2021 12:07:04 -0400 (EDT)
Subject:        	Re: Directories
To:             	python-list@cwi.nl
smoothasice@geocities.com writes:
>Hi, i'm curious if there is a python command or set of commaneds that
>could be used like the dir() command in dos prompt.  I am trying to write
> a program in python that would allow me to list the files of a certain
>data type in a few directories but I need to know how I would do
 There are a few ways of doing this.  
 * os.listdir(path) returns a list containing the names of all
the files in the directory specified by path.
"""
import os
print os.listdir('.')
# e.g. ['Group.java', 'Group.class', 'User.java', ... ]
"""
 So you can do os.listdir('C:/whatever/sub/dir/ectory'), and
then loop over each filename with a for loop.
 * The glob module returns a list of filenames matching a
wildcard pattern.  
"""
import glob
print glob.glob('*.java')
# e.g. ['Group.java', 'User.java', 'GroupWrapper.java', ... ]