使用Python导入文件夹中的文件夹名称列表

2024-09-22 20:28:41 发布

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

所以我又开始尝试自动化一些东西。我的最终任务是合并Excel文件中包含文件名中清理的数据,并合并这些文件中名为LOV的选项卡中的数据。所以基本上它必须进入一个文件夹,文件夹中有两个文件,其中一个文件在命名中有单词Clean Up,是一个.xlsx文件。我只需要读取这些文件,然后将标签LOV中的数据拉到一个大文件中。---所以这就是我的最终目标。我刚刚开始,我不在附近,但现在你知道最后的比赛。你知道吗

目前我被困只是在主文件夹的文件夹名称列表,所以我至少知道它得到那里哈哈

import os
import glob
import pandas as pd


# assigns directory location to PCC Folder
os.chdir('V:/PCC Clean Up Project 2017/_DCS Data SWAT Project/PCC Files 
Complete Ready to Submit/Brake System Parts')
FolderList = glob.glob('')

print(FolderList)

enter image description here

  • 谢谢大家的帮助!你知道吗

Tags: 文件to数据importproject文件夹cleanos
2条回答

如果只需要当前目录中的文件夹列表,可以使用os.path。其工作原理如下:

import os
directory = "V:/PCC Clean Up Project 2017/_DCS Data SWAT Project/PCC Files 
Complete Ready to Submit/Brake System Parts"
childDirectories = next(os.walk(directory))[1]

这将为您提供当前目录中所有文件夹的列表。你知道吗

阅读更多关于os.walkhere。你知道吗

然后可以使用os.chdir进入其中一个子目录:

os.chdir(childDirectories[i])

编辑

首先你的问题很难理解。但据我所知,你需要遍历文件夹和子文件夹,你可以用

for root, dirs, files in os.walk(source): #Give your path in source
    for file in filenames:
        if file.endswith((".xlxs")): # You can check for any file extension
           filename = os.path.join(subdir,file)
           dirname = subdir.split(os.path.sep)[-1]  # gets the directory name
           print(dirname)

相关问题 更多 >