How to use the os module to traverse files in a directory in Python 3.x
In Python, we can use the os module to operate files and directories. The os module is an important module in the Python standard library, providing many operating system-related functions.
In this article, we will introduce how to use the os module to traverse all files in a directory. First, we need to import the os module:
import os
Next, we can use the os.walk()
function to traverse the directory. os.walk()
The function will return a generator, and each iteration will return a triplet (current directory path, list of directory names in the current directory, list of file names in the current directory )
. We can use a for loop to iterate through this generator to get all the files in the directory.
Here is a sample code that demonstrates how to use the os module to iterate through all files in a directory and print their paths:
import os def traverse_directory(directory): for root, dirs, files in os.walk(directory): for file in files: file_path = os.path.join(root, file) print(file_path) # 遍历当前目录 current_dir = os.getcwd() traverse_directory(current_dir)
In this example, we define a file called traverse_directory()
function to traverse the directory. The parameter directory
of the function is a string representing the directory path to be traversed.
Inside the function, we use os.walk(directory)
to traverse the directory. In each iteration, root
represents the path of the current directory, dirs
is the list of subdirectories under the current directory, and files
is the list of files under the current directory.
Next, we use a for loop to traverse the files
list to obtain the file names in the current directory. We use the os.path.join()
function to splice the current directory path and file name to get the full path of the file.
Finally, we use the print()
function to print the path of the file.
At the end of the sample code, we call the traverse_directory()
function and pass in the path of the current directory to traverse and print all file paths in the current directory.
In addition to printing the file path, we can also perform other operations inside the function, such as reading file content, copying files, etc.
Summary:
This article introduces how to use the os module in Python 3.x to traverse files in a directory. We used the os.walk()
function to traverse the directory and operate on each file. This sample code can serve as a base and you can extend it to suit your needs. In practical applications, traversing directories is a common task, and mastering this skill will provide you with a lot of convenience.
The above is the detailed content of How to use the os module to traverse files in a directory in Python 3.x. For more information, please follow other related articles on the PHP Chinese website!