在处理数据的时候,经常需要遍历,目录下的所有文件夹,或者所有目录的文件,一般遍历有递归,跟python自带的os.walk()方法,下面我们就来讲下os.walk()的实际应用
1.遍历所有目录名称并把所有目录路径保存的txt文本
import os
"""
遍历所有文件夹
"""
fn = open('dir.txt','w')
for root,dirs,files in os.walk(r"D:\code\test"):
for dir in dirs:#遍历文件夹
dirPath =os.path.join(root, dir) #拼接目录路径
fn.write(dirPath + '\n')
fn.close()
2.遍历所有文件名并且拼接路径,把文件路径保存文本
import os
"""
遍历所有文件并且保存文件路径
"""
fn = open('files.txt','w')
for root,dirs,files in os.walk(r"D:\code\test"):
for f in files:#遍历文件夹
dirPath =os.path.join(root, f) #拼接文件名路径
fn.write(dirPath + '\n')
fn.close()