首页 > 解决方案 > 如何获取具有完整路径的子文件夹文件列表?

问题描述

我想获得与这种方法相同的列表结构,但我得到了一个完整的列表,而我必须手动分解它,它会杀死“自动化任务”。

例如,我有一个test名为 A、B、C、D 的 4 个子文件夹的文件夹,在每个文件夹中我们可以找到文件 file1、file2、file3。

import os
import openpyxl
#Create a regex that matches files with the american date format
path = r'C:\Users\Dell_G7_15\Desktop\test'
pathWalk = os.walk(path)
fileIndex = os.listdir(path)
wb = openpyxl.Workbook()
i=0
filenames = []
filesPathLink=[]
for foldernames in pathWalk:
    filenames.append(foldernames[-1])   #creating list of filenames
    i= i+1
filenames.pop(0) #delete first value of the list that causes error 
print(filenames)

当我打印文件名时,我得到:

[['file1', 'file2', 'file3'],['file1', 'file2', 'file3'],['file1', 'file2', 'file3']]

我正在寻找相同的列表结构,但要获得每个列表的完整路径,它看起来像这样:

[['../A/file1', '../A/file2', '../A/file3'],[....],[....]]

标签: python

解决方案


这是你想要的?

对于以下文件夹和子文件夹 -

# root/
#    -img0.jpg
#    sub1/
#       -img1.jpg
#       -img1 copy.jpg
#    sub2/
#       -img2.jpg
#       subsub1/
#           -img3.jpg

path = '/Users/name/Desktop/root'

[[r+'/'+fname for fname in f] for r,d,f in os.walk(path)]
[['/Users/name/Desktop/root/img0.jpg'],
 ['/Users/name/Desktop/root/sub1/img1 copy.jpg',
  '/Users/name/Desktop/root/sub1/img1.jpg'],
 ['/Users/name/Desktop/root/sub2/img2.jpg'],
 ['/Users/name/Desktop/root/sub2/subsub1/img3.jpg']]

为了完整起见,如果有人正在寻找具有多级文件夹结构内路径的所有文件的平面列表,那么试试这个 -

[r+'/'+fname for r,d,f in os.walk(path) for fname in f]
['/Users/name/Desktop/root/img0.jpg',
 '/Users/name/Desktop/root/sub1/img1 copy.jpg',
 '/Users/name/Desktop/root/sub1/img1.jpg',
 '/Users/name/Desktop/root/sub2/img2.jpg',
 '/Users/name/Desktop/root/sub2/subsub1/img3.jpg']

编辑:没有列表理解的简单循环

filepaths = []
for r,d,f in os.walk(path):
    l = []
    for fname in f:
        l.append(r+'/'+fname)
    filepaths.append(l)

print(filepaths)
[['/Users/name/Desktop/root/img0.jpg'],
 ['/Users/name/Desktop/root/sub1/img1 copy.jpg',
  '/Users/name/Desktop/root/sub1/img1.jpg'],
 ['/Users/name/Desktop/root/sub2/img2.jpg'],
 ['/Users/name/Desktop/root/sub2/subsub1/img3.jpg']]

推荐阅读