os.walk(arcpy.env.workspace) retur only files from the root folder

806
5
06-07-2018 06:57 AM
JoseSanchez
Occasional Contributor III

Hello everyone,

How do I read only files from the root folder?

for (path, dirs, files) in os.walk(arcpy.env.workspace):

      for file in files:

            print file

0 Kudos
5 Replies
JoshuaBixby
MVP Esteemed Contributor
JoseSanchez
Occasional Contributor III

just add a break

for (path, dirs, files) in os.walk(arcpy.env.workspace):

      for file in files:

            print file

......

#

# os.walk read only the root folder

#

   break

0 Kudos
JonathanQuinn
Esri Frequent Contributor

I'd use os.listdir:

>>> import os
>>> myFiles = os.listdir(r"C:\Users\jona6782\Documents\ArcGIS")
>>> print(myFiles)
['49058003.jpg', 'AddIns', 'c5A5E1C002DC8445A8FC05C471B1.json', 'Default.gdb', 'GeoNet', 'happy.png', 'JQNew - Copy.sd', 'JQNew.sd', 'LotsOfData.mxd', 'MyProject8.ppkx', 'MyService123.sd', 'New Folder', 'OnlineProjects', 'Packages', 'Portland.slpk', 'Projects', 'ProjectTemplates', 'ProPortalData', 'Rotterdam.slpk', 'scratch', 'scratch.gdb', 'Shapefiles', 'TilingSchemes', 'Toolbox.tbx', 'worldcities.gdb', 'WorldCities.mxd', 'WorldCitiesPG.mxd']

It will return a list of the files/folders in a specific directory.

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

But with os.walk you know you are only getting files, with os.listdir you need to do additional steps to determine the type of file system object.

0 Kudos
JonathanQuinn
Esri Frequent Contributor

Oops, missed the "only files" part. os.path.isfile can be used as well, then:

python - List files in ONLY the current directory - Stack Overflow 

As always, lots of ways to do the same thing.

0 Kudos