How to get all file names in a specified directory in Python

As mentioned in "Operation of File Names and Paths in Python" , functions in the os module can operate on files. Through recursion and the functions provided in the os module, you can get all the file names in the specified directory.

1 Basic process

The basic process of recursively obtaining all file names in a specified directory is shown in Figure 1.

Figure 1 Basic process

2 function implementation

2.1 Define the function

Define a function called walk. This function has a parameter dirname, which indicates the specified current directory. The code is as follows:

def walk(dirname):

2.2 Obtain and access all subfolder names and file names in the current directory

As mentioned in "Operation of File Names and Paths in Python", you can use the os.listdir() function to obtain all subfolder names and file names in the specified directory. Therefore, in the walk() function content, there is the following code:

for name in os.listdir(dirname):

The above code accesses all subfolder names and file names obtained by the os.listdir() function through a for loop, and saves them in the variable name.

2.3 Get the absolute path of the file

Inside the for loop, use the os.path.join() function to obtain the absolute path of the file. The code is as follows:

path = os.path.join(dirname, name)

Among them, the os.path.join() function is to connect the folder name and the file name, the parameter dirname is the parameter of the walk() function, which is the folder name; the parameter name is the subfile obtained by the os.listdir() function folder or file name. Finally, the obtained absolute path is stored in the variable path.

2.4 Determine whether it is a file

Inside the for loop, after obtaining the absolute path path, the next step is to determine whether the path is a file, the code is as follows:

if os.path.isfile(path):
   print(path)
else:
   walk(path)

In the above code, if the path is a file, the file name will be printed out; if the path is not a file, it means that it is a subfolder, and the walk() function is called recursively to display all the file names in the path subfolder.

3 function calls

To get all the file names of the directory where the current Python source file is located, you can use the following code to achieve:

cwd = os.getcwd()
walk(cwd)

Among them, the os.getcwd() function obtains the directory where the current Python source file is located, passes the directory as a parameter to the walk() function, and obtains all file names in the directory.

4 complete code

The complete code of the program is as follows:

import os

def walk(dirname):
    for name in os.listdir(dirname):
        path = os.path.join(dirname, name)

        if os.path.isfile(path):
            print(path)
        else:
            walk(path)

cwd = os.getcwd()
walk(cwd)

Guess you like

Origin blog.csdn.net/hou09tian/article/details/131498580