目录列表,保存每个文件

2024-10-03 02:34:48 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试创建一个列表,使每个列表值都包含根目录和该根目录中的每个文件,使每个列表值最终看起来像:

Z:\Clients\xxx\2。原始出口\ A区\“A\u bund-a8010.fls”“A\u bund-a9000.fls”


Tags: 文件列表xxx根目录clientsflsbunda9000
2条回答

我想我已经做到了,我肯定可以做得更好,但是:

import os

rootFolder = ("C:\\Users\\ALS_Surveying\\Desktop\\test folder")

# Creates a list of all subfolders
subFolderList = os.listdir(rootFolder)

# This create the full path to each subfolder
subFolderList2 = []
for a in subFolderList:
   temp = os.path.join(rootFolder,a)
   subFolderList2.append(temp)  

# How many subfolders in root
totalSubFolders = len(subFolderList)


# Creates a List holding a single value for all contents in each subfolder
fileList = []
stepper = 0
for fl in range(totalSubFolders):
   fileList.append(os.listdir(subFolderList2[stepper]))
   stepper = stepper + 1


# Create the final list holding the full path, root to files
filePathList = []
stepper = 0
for final in range(totalSubFolders):
   subFolderList2Var = str(subFolderList2[stepper])
   fileListVar = str(fileList[stepper])
   temp2 = os.path.join(subFolderList2Var,fileListVar)
   stepper = stepper + 1
   filePathList.append(temp2)

喜欢听你的想法

我不清楚如何为每个子文件夹部分创建列表。你知道吗

如果你想

<强>1。创建一个包含所有目录(包括根文件夹)的列表:创建一个列表,然后为每个子文件夹将其附加到列表中

list = ["rootfolder directory"]
for subfolder in rootfolder:
   list.append(subfolder)

<强>2。创建一个包含所有目录的列表,这些目录可以通过根文件夹的名称找到:上面的方法将通过查找第一个项目(即根目录)来工作。但我建议用字典

dirdic = {}  #First initialize a new dictionary
dirdic['rootfolder'] = [] #Make a new dictionary item
for subfolder in rootfolder:
   dirdic['rootfolder'].append(subfolder)

这样您就可以编辑列表,为每个根目录创建一个新的列表对象,只需搜索字典就可以找到子文件夹列表。你知道吗

相关问题 更多 >