Home >Backend Development >Python Tutorial >Python recursively prints all files under the specified path

Python recursively prints all files under the specified path

巴扎黑
巴扎黑Original
2016-12-07 11:33:211301browse

Enter a path to display all subdirectories under the file.

import os
def list_all_path(path):
    if os.path.isfile(path):
        print(path);
        global count;
        count+=1
        print(count);
    else:
        if os.path.isdir(path):
            for sub_path in os.listdir(path):
                list_all_path(path+"/"+sub_path);
                #这个路径很关键,要绝对路径,否则没法递归
count=0;
my_dir=input("输入一个路径:");
list_all_path(my_dir);

count is a statistical number

The operation effect is as follows:

输入一个路径:d:/workspaces
d:/workspaces/MyEclipse 8.5/.metadata/.bak_0.log
1
d:/workspaces/MyEclipse 8.5/.metadata/.lock
2
d:/workspaces/MyEclipse 8.5/.metadata/.log

With this program, you can filter out all files that contain a certain keyword in the file name by adding a judgment statement. The effect is similar to that under Windows global search. Will continue to update later.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn