Python traverses all files in a folder

藏色散人
Release: 2020-10-22 10:25:38
Original
28811 people have browsed it

How python traverses all files in a folder: first open the corresponding code file; then traverse all files through "for f in files:print(os.path.join(root, f))" Just clip it.

Python traverses all files in a folder

Recommended: "python video tutorial"

python traverses all files in the folder

Basic

import os
# 遍历文件夹
def walkFile(file):
    for root, dirs, files in os.walk(file):
        # root 表示当前正在访问的文件夹路径
        # dirs 表示该文件夹下的子目录名list
        # files 表示该文件夹下的文件list
        # 遍历文件
        for f in files:
            print(os.path.join(root, f))
        # 遍历所有的文件夹
        for d in dirs:
            print(os.path.join(root, d))
def main():
    walkFile("f:/ostest/")
if __name__ == '__main__':
    main()
Copy after login

Advanced

Calculate the number of lines of code in the py file in the folder

total_num = 0
for base_path,folder_list,file_list in os.walk(target_path):
    for file_name in file_list:
        file_path = os.path.join(base_path,file_name)
        file_ext = file_path.rsplit('.',maxsplit=1)
        if len(file_ext) != 2:
            # 没有后缀名
            continue
        if file_ext[1] != 'py':
            # 不是py文件
            continue
        file_num = 0
        with open(file_path,'rb') as f:
            for line in f:
                # 去空格
                line = line.strip()
                if not line:
                    continue
                # 去除 # 注释
                if line.startswith(b'#'):
                    continue
                file_num += 1
        total_num += file_num
Copy after login

The above is the detailed content of Python traverses all files in a folder. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!