问题
I use os.listdir
and it works fine, but I get sub-directories in the list also, which is not what I want: I need only files.
What function do I need to use for that?
I looked also at os.walk
and it seems to be what I want, but I\'m not sure of how it works.
回答1:
You need to filter out directories; os.listdir()
lists all names in a given path. You can use os.path.isdir() for this:
basepath = '/path/to/directory'
for fname in os.listdir(basepath):
path = os.path.join(basepath, fname)
if os.path.isdir(path):
# skip directories
continue
os.walk()
does the same work under the hood; unless you need to recurse down subdirectories, you don't need to use os.walk()
here.
回答2:
Here is a nice little one-liner in the form of a list comprehension:
[f for f in os.listdir(your_directory) if os.path.isfile(os.path.join(your_directory, f))]
This will return
a list
of filenames within the specified your_directory
.
回答3:
import os
directoryOfChoice = "C:\\" # Replace with a directory of choice!!!
filter(os.path.isfile, os.listdir(directoryOfChoice))
P.S: os.getcwd() returns the current directory.
回答4:
for fname in os.listdir('.'):
if os.path.isdir(fname):
pass # do your stuff here for directory
else:
pass # do your stuff here for regular file
来源:https://stackoverflow.com/questions/22207936/python-how-to-find-files-and-skip-directories-in-os-listdir