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.
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()
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
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!