python USES os.listdir and os.walk to get the path to the file

  • 2020-06-15 09:46:30
  • OfStack

This article introduces python's method of using os.listdir and os.walk to get the path of the file. The details are as follows:

The os. listdir() method is used to return a list of the files or folder names that the specified folder contains. The list is in alphabetical order. It does not include '.' and '. 'even though it's in the folder.

The os. walk() method is used to output the filename in the directory by walking through the directory tree species, up or down.

os.listdir: You can use os.listdir when there are only files under 1 directory and no folders

We have an file directory (folder) on our desktop with three files in it


Get the absolute path to the file using the following procedure:

import os
path = r'C:\Users\Administrator\Desktop\file'
for filename in os.listdir(path):

os. listdir is used to read all the file names under a directory, and then os. path. join is used to combine the path of the directory and the file name.


Case 2: Recursive case, 1 directory under both directories (directory under which there may be directories and files) and how to read all the files inside, using ES47en.walk:

os. walk introduction:

We set up an file directory on the desktop. The organizational structure is as follows:


Run the following code:

import os
path = r'C:\Users\Administrator\Desktop\file'
for dirpath,dirnames,filenames in os.walk(path):

The output results are as follows:

C:\Users\Administrator\Desktop\file ['file1', 'file2'] ['file_test1.txt', 'file_test2 .txt']
C:\Users\Administrator\Desktop\file\file1 [] ['file1_test1.txt', 'file1_test2.txt']
C:\Users\Administrator\Desktop\file\file2 [] ['file2_test1.txt']

os. walk enter 1 path name, return 1 3 tuple dirpath, dirnames, filenames as yield (actually a generator),

dirpath is the path to the directory, which is 1 string. For example, C:\Users\ Desktop\file \Administrator\ file\file1 and so on.

dirnames lists the names of all existing directories under the directory path. For example, under C:\Users\Administrator\Desktop\ file1 and file2, it lists the directory name under this directory path.

filenames lists the names of all the files under the directory path. Also under C:\Users\ Desktop\file there are two files file_ES119en1.txt and file_ES122en2.txt which will be listed by the program.

How to get 1 path for all the following file paths:

import os
path = r'C:\Users\Administrator\Desktop\file'
for dirpath,dirnames,filenames in os.walk(path):
 for filename in filenames:

The results are as follows:

C:\Users\Administrator\Desktop\file\file_test2 .txt

Related articles: