打印指定路径下所有文件的具体路径
打印指定路径下所有文件的具体路径
import os
input_path = './'
path_file = open('path_file', 'w')
for root, dirs, files in os.walk(input_path):
for file in files :
path_file.write(os.path.join(root,file)+'\n')
path_file.close()
os.walk() 方法
os.walk(top[, topdown=True[, onerror=None[, followlinks=Flase]]])
top--是所要遍历的目录地址,返回的是一个三元组(root, dirs, files)
- root--指的是当前正在遍历的这个文件夹的本身的地址
- dirs--一个list,内容是该文件夹中所有的目录的名字(不包括子目录)
- files--一个list,内容是该文件夹中所有的文件(不包括子目录)
Example
import os
input_path = './'
path_file = open('path_file.txt', 'w')
for root, dirs, files in os.walk(input_path):
path_file.write(f'root = {root}\n')
for dir in dirs:
path_file.write(f'dir = {dir}\n')
for file in files :
path_file.write(f'file = {file}\n')
path_file.write('root+file = '+os.path.join(root,file)+'\n')
path_file.close()
结果
root = ./
dir = 110
dir = 111
dir = 112
file = path_file.txt
root+file = ./path_file.txt
file = print_path.py
root+file = ./print_path.py
file = select_img.py
root+file = ./select_img.py
file = Test_10.py
root+file = ./Test_10.py
root = ./110
dir = 222
root = ./110\222
root = ./111
root = ./112
dir = 221
root = ./112\221
dir = 333
root = ./112\221\333
实际结构如图,其原理就是遍历树。