Python list directory, subdirectory, and files
Use os.path.join
to concatenate the directory and file name:
for path, subdirs, files in os.walk(root):
for name in files:
print(os.path.join(path, name))
Note the usage of path
and not root
in the concatenation, since using root
would be incorrect.
In Python 3.4, the pathlib module was added for easier path manipulations. So the equivalent to os.path.join
would be:
pathlib.PurePath(path, name)
The advantage of pathlib
is that you can use a variety of useful methods on paths. If you use the concrete Path
variant you can also do actual OS calls through them, like changing into a directory, deleting the path, opening the file it points to and much more.
Getting a list of all subdirectories in the current directory
Do you mean immediate subdirectories, or every directory right down the tree?
Either way, you could use os.walk
to do this:
os.walk(directory)
will yield a tuple for each subdirectory. Ths first entry in the 3-tuple is a directory name, so
[x[0] for x in os.walk(directory)]
should give you all of the subdirectories, recursively.
Note that the second entry in the tuple is the list of child directories of the entry in the first position, so you could use this instead, but it's not likely to save you much.
However, you could use it just to give you the immediate child directories:
next(os.walk('.'))[1]
Or see the other solutions already posted, using os.listdir
and os.path.isdir
, including those at "How to get all of the immediate subdirectories in Python".
Find all files in a directory with extension .txt in Python
You can use glob
:
import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
print(file)
or simply os.listdir
:
import os
for file in os.listdir("/mydir"):
if file.endswith(".txt"):
print(os.path.join("/mydir", file))
or if you want to traverse directory, use os.walk
:
import os
for root, dirs, files in os.walk("/mydir"):
for file in files:
if file.endswith(".txt"):
print(os.path.join(root, file))
list all files in directory under different user python
os.listdir
returns the filename without path, which makes it a relative path based on source_folder
. os.path.abspath
doesn't know about source_folder
. All it knows about is the current working directory. So, it assumes CWD is the relative path that you want to be made absolute.
You could join the known path component before making it absolute
files = [os.path.abspath(os.path.join(source_folder, x))
for x in os.listdir(source_folder)]
When using Path
you have a similar problem. You created the path from the filename which lacks its path component, so Path
assumes you meant the current working directory. Instead have Path
do the directory enumeration for you so that it passes back properly qualified Path
objects.
files = [x.absolute() for x in Path(source_folder).glob("*")]
List files ONLY in the current directory
Just use os.listdir
and os.path.isfile
instead of os.walk
.
Example:
import os
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
# do something
But be careful while applying this to other directory, like
files = [f for f in os.listdir(somedir) if os.path.isfile(f)]
which would not work because f
is not a full path but relative to the current directory.
Therefore, for filtering on another directory, do os.path.isfile(os.path.join(somedir, f))
(Thanks Causality for the hint)
Related Topics
Pandas Fill Missing Values in Dataframe from Another Dataframe
Take the Content of a List and Append It to Another List
Underscore VS Double Underscore with Variables and Methods
Run Child Processes as Different User from a Long Running Python Process
Differencebetween Encode/Decode
Importerror: No Module Named Matplotlib.Pyplot
Checking If All Elements in a List Are Unique
Strange Behavior of Lists in Python
Generating Matplotlib Graphs Without a Running X Server
How to Access Pandas Groupby Dataframe by Key
Get Raw Post Body in Python Flask Regardless of Content-Type Header
Python - Add Pythonpath During Command Line Module Run
Principal Component Analysis (Pca) in Python