Select to view content in your preferred language

Python Novice Question - Get a list of files in a directory with particular extension

2589
15
08-20-2010 07:32 AM
SheriNorton
Frequent Contributor
I need to generate a list of all files in a directory with a *.MDB extension (personal geodatabases) in a Python script. Should I first split the path and filenames:

dirname = "C:\Arcwork"
(filepath, filename) = os.path.split(dirname)

and then somehow split the filename into name and extension (how?!), or vice versa?
0 Kudos
15 Replies
Luke_Pinner
MVP Regular Contributor
Both code snippets will work on Windows and unix/linux, but the top one will only return *.mdb (not *.MDB/*.MdB/etc...) on unix/linux as those OSs have case-sensitive file systems (generally speaking, as there are case-insensitive types of filesystems for linux and you can enable case-sensivity for certain Windows filesystems).
0 Kudos
TedCronin
MVP Alum
There is also a new List at ArcGIS 10 called ListFiles, arcpy.ListFiles ("*.mdb").
0 Kudos
DanielSmith
Frequent Contributor
i like using:


for root, dirs, files in os.walk(r'your root directory'):


that way you can access directories and files independently.
0 Kudos
NiklasNorrthon
Frequent Contributor
Here are two more ways to do this:

import os
personal_gdbs = [file for file in os.listdir('c:/Arcwork' if file.lower().endswith('.mdb')]


or


import arcpy
arcpy.env.workspace = 'c:/Arcwork'
personal_gdbs = arcpy.ListWorkspaces('*.mdb')
0 Kudos
HugoAhlenius
Deactivated User


import os
personal_gdbs = [file for file in os.listdir('c:/Arcwork') if file.lower().endswith('.mdb')]



To me, this looks like cleanest!
(I corrected a paranthesis in the snippet)
0 Kudos
TedCronin
MVP Alum
This is a great thread.
0 Kudos