一、os.walk(path)
返回的是一个三元组,以传入的参数path为起点,得到这个起点路径(root),这个起点下的所有的文件夹list(dirs),这个起点下的所有的文件list(files)
三元组为(root,dirs,files)
常用的操作:输出所有文件的完整路径
os.path.join(root, file)
把root跟文件名连接起来(注意不是字符串的简单拼接,因为两个中间可能有子文件夹)
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))
二、如何得到文件上一级文件夹名
/Users/dir/test.txt
想得到test.txt的上一级文件夹名“dir”,找了半天没有找到函数
但是仔细想就是一个字符串的剪切问题‘
for f in files:
path = os.path.join(root, file)
print(path.split('/')[-2])
附官方文档https://docs.python.org/3/library/os.html#os.scandir