Photo: By Instagram

It takes about 6 minutes to read the text.

Hidden files and hidden folders exist in both Windows and Linux systems. Hidden folders are system-critical directories, for example, the Boot folder or Windows folder on the C disk in Windows. In Linux, some system configuration files or software configuration files are hidden, for example, the system environment variable profile.profile. Sometimes we have to traverse the entire directory through the file path to find hidden files. The main content of this article is to share three ways Python can traverse a file.

Suppose you have a folder called “Python” on disk E; This folder also has two folders, “A” and “B”; There is also A “results.txt” text file in the “A” folder. Therefore, the file structure of the “Python” folder is as follows:

Python|--A|  |--results.txt|--B

Copy the code

As we can see from the above, a folder is actually a tree data structure. The simplest and most violent way to traverse a tree is recursion. So the code to traverse the “Python” folder could be written like this.

# -* -coding: utF-8 -*-import OS # def traversal_files(path): for dir in os.listdir(path): Join (path, dir) print(dir) # if os.path.isdir(dir): traversal_files(dir)if __name__ == '__main__': path = '.' traversal_files(path)

Copy the code

When you run the script, you find that the files and folders in “Python” are printed out.

Can this traversal find hidden files? The answer is yes. Let’s put it to the test. First, we put a hidden “config.txt” file in the “Python” folder.

Then run the program again, only to find that “config.txt” is printed.

While this approach is simple to write, it can be inefficient if the subdirectory level of the folder is too deep.

Since recursion is too violent, using os.walk() makes the program elegant. The os.walk() method is an easy-to-use file/directory traverser that helps you efficiently process files/directories. This method works on Linix and Windows.

The common use of os.walk() is to pass in two arguments. The first argument is path, which is the address of the directory to traverse. It returns a triple (root, dirs, files).

  • Root refers to the address of the folder itself that is being traversed

  • Dirs is a list of the names of all directories in that folder (excluding subdirectories)

  • Files is also a list of all files in this folder (excluding subdirectories).

The second argument is topDown, which is optional. When its value is True, the path directory is traversed first, otherwise the subdirectories of top are traversed first (on by default).

So, walk through the folder using os.walk to find the code for the hidden files as shown below.

# -*- coding: UTF-8 -*-import osdef traversal_files(path):    for root, dirs, files in os.walk(path, topdown=False):        for name in files:            print(os.path.join(root, name))        for name in dirs:            print(os.path.join(root, name))if __name__ == '__main__':    path = '.'    traversal_files(path)

Copy the code

In Python 3.5, the os.scandir() method, which is a directory iteration method, was added. Os.scandir () runs more efficiently than os.walk. In PEP 471, Python also officially recommends that we use os.scandir() to traverse the directory.

Following the previous example, the code for traversing the hidden files in the “Python” folder is as follows:

# -*- coding: UTF-8 -*-import osdirs = []files = []def traversal_files(path):    for item in os.scandir(path):        if item.is_dir():            dirs.append(item.path)        elif item.is_file():            files.append(item.path)    print('dirs:', dirs)    print('files:', files)if __name__ == '__main__':    path = '.'    traversal_files(path)

Copy the code

Run the result, also can find hidden files.

If you think the article is good, please like it and share it. Your affirmation is my biggest encouragement and support.

Recommended reading:

Python has such a weird library –The Fuck

Scrapy middle key

10 charts to take you through the evolution of backend services architecture

High concurrency stuff

A thousand miles is a short step