python - 如何获取具有完整路径的子文件夹文件列表?
问题描述
我想获得与这种方法相同的列表结构,但我得到了一个完整的列表,而我必须手动分解它,它会杀死“自动化任务”。
例如,我有一个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'],[....],[....]]
解决方案
这是你想要的?
对于以下文件夹和子文件夹 -
# 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']]
推荐阅读
- java - 单链表 - 获取和添加方法
- php - 为什么不在 php 中使用 Google_Oauth2Service 接收电子邮件地址?
- python - 程序通过连接两个字符串都不包含的字符从两个给定的字符串创建一个字符串
- python - 根据另一个键的值的第一次出现替换键的值
- javascript - 使用 express 发送和接收数据
- ios - iOS 13 中的 viewDidAppear 问题
- nosql - 使用 MarkLogic 进行计数
- python - 完美号码列表器
- javascript - javascript中的焦点元素无法在画外音中进入组,直到取消焦点组,然后使用画外音键导航回组
- html - 如何让我的文字贴在响应式 div 上?