Python implements directory file scanning function

In daily program writing, we often encounter the function of obtaining files in the directory, so we will briefly organize this function for your reference.

The most commonly used method for traversing directory files is os.listdir(), and there is also a os.walk method.
1. os.listdir method

The description of the method in the source code is “Return a list containing the names of the files in the directory.” The input parameter is a directory, and all file names under the directory are returned in the form of a list. The returned list is unordered, but does not include the special entries “.”, “..”, even if they exist in the directory.

The syntax format is as follows:

  1. os.listdir(path)

Take a chestnut:

1 def get_dirnames(filePath):
2 lists = os.listdir(filePath)
3 # Print to get the list information of files name
4 print(lists)
5 # Call the method and pass in the specified directory
6 get_dirnames("D:\Python_location\Demo03\ddt_demo")

Results of the:

Return list information['10.txt', '121212.txt', '1232323.py', '21.txt', '2121.py', 'ddt_test.py', 'send_email.py', ' __init__.py'] is unordered.

Through listdir, only the file names in the current path are obtained, excluding files in subdirectories. If you need to get all files, you can use the recursive method. You can refer to the following demo:

 1 def get_dirnames(filePath):
 2 print("\
 ************* listdir demo *************")
 3 print("current dir : {0}". format(filePath))
 4 lists = os.listdir(filePath)
 5 # Print to get the list information of files name
 6 print(lists)
 7 for cur_file in lists:
 8 # Traverse the file names in lists and splicing filePath to get a new path or file absolute path
 9 path = os.path.join(filePath, cur_file)
10 # Determine whether the new path is a file: if it is a file, you do not need to continue to check, if it is a directory, you need to continue to traverse the file names in the directory
11 # if os.path.isfile(path):
12 # print("{0} is file!". format(cur_file))
13 if os.path.isdir(path):
14 # print("{0} is dir!". format(cur_file))
15 # If it is a directory, continue to recurse the directory, and repeatedly call the get_dirnames method to recurse the directory
16 get_dirnames(path)
17 # Call the method and pass in the specified directory
18 get_dirnames("D:\Python_location\Demo03\ddt_demo")

Actual directory:

operation result:

Output all file information in a directory directory by directory. All file names can be obtained, but it is inconvenient to quote. The following code is for reference.

 1 import os
 2 def new_report(testreport):
 3 """
 4 Generate the latest test report file
 5 :param testreport:
 6 :return: return file
 7 """
 8 lists = os.listdir(testreport)
 9 lists.sort(key=lambda fn: os.path.getmtime(testreport + "" + fn))
10 file_new = os.path.join(testreport, lists[-1])
11 return file_new

1. Read all file names in the specified directory

2. After sorting (arranged in chronological order in the project), take the latest file

3. Return value (full name of the latest file)

2. os.walk method

The os.walk() method is used to output the filenames in a directory by walking in the directory tree, up or down. It is a simple and easy-to-use file and directory traverser, which can help us deal with files and directories efficiently.

The syntax format is as follows:

os. walk(top, topdown=True, onerror=None, followlinks=False)

Method parameter description:

  • top: the path of the directory to traverse
  • topdown: optional, if it is True, it will first traverse the top directory and each subdirectory under the top directory, otherwise it will first traverse the subdirectories of top, the default is True
  • onerror: optional, requires a callable object, called when walk is abnormal
  • followlinks: optional, if it is True, it will traverse the directory actually pointed to by the shortcut in the directory (symbolic link in Linux), the default is False
  • args: Contains a list of arguments without ‘-‘ or ‘-‘

Return value: triplet (dirpath, dirnames, filenames)

  • dirpath : refers to the address of the directory currently being traversed
  • dirnames : a list of all directory names in the current folder (excluding subdirectories)
  • filenames: all files in the current folder (excluding files in subdirectories)
 1 import os
 2 def get_file_name(filePath):
 3 ab = os. walk(filePath)
 4 for i, j, k in ab:
 5 print("********print the contents of i**************")
 6 print(i)
 7 print("********print the contents of j**************")
 8 print(j)
 9 print("********print the content of k**************")
10 print(k)
11 get_file_name("D:\Python_location\Demo03\ddt_demo\dsldls")

Directory Structure:

operation result:

3. Other common methods related to files

os.path.splitext() separates file name and file extension

  1. file = "test.txt"
  2. file_name = os.path.splitext(file)[0]
  3. file_suffix = os.path.splitext(file)[1]
  4. # Execution result, file_name: text file_suffix: .txt

os.path.exists: Determine whether a file or directory exists

os.path.isfile(): Determine whether it is a file

os.path.isdir(): Determine whether it is a directory

os.path.dirname(): Get the directory where the current file is located, that is, the parent directory

"""This method is often used to obtain the directory of the current file, and use this to obtain the root directory as the base directory, and splice the path to obtain the file"""
# Get the directory where the current file is located
os.path.dirname(__file__)
# Get the parent directory of the directory where the current file is located (the root directory of the project in the general framework)
os.path.dirname(os.path.dirname(__file__))

os.makedirs(): create a multi-level directory

os.makedir(): Create a single-level directory

os.path.getsize(): Get file size

The above content is the main content of this sharing, and I hope it can be helpful to everyone in their work and study! grateful!

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Python entry skill tree advanced grammar file 257177 people are studying systematically