Python:将目录和文件名存储为数据帧列

Python:将目录和文件名存储为数据帧列,python,file,pandas,directory,subdirectory,Python,File,Pandas,Directory,Subdirectory,我想读取在每个目录中有多个文件夹和文件的目录的内容,并将文件夹和文件名指定为数据帧列的值。目录是“home”,其中每个文件夹中有几个文件夹和文件。对于该特定文件夹中存在的尽可能多的文件,“文件夹”列将重复。输出数据帧如下所示: Folder File a_folder a_file a_folder b_file a_folder c_file b_folder aa_file b_folder bb_File b_folder cc_File etc... 到目前为止,我正在尝试的是: i

我想读取在每个目录中有多个文件夹和文件的目录的内容,并将文件夹和文件名指定为数据帧列的值。目录是“home”,其中每个文件夹中有几个文件夹和文件。对于该特定文件夹中存在的尽可能多的文件,“文件夹”列将重复。输出数据帧如下所示:

Folder  File
a_folder a_file
a_folder b_file
a_folder c_file
b_folder aa_file
b_folder bb_File
b_folder cc_File
etc...
到目前为止,我正在尝试的是:

import os
import pandas as pd

folders = []
files = []
df = pd.DataFrame(columns=['Folder', 'File'])

for folder in sorted(os.listdir('home')):
    folders.append(folder)  
    for file in sorted(os.listdir('home/'+folder)):
        files.append(file)

df['Folder']=folders
df['File']=files

但很明显,我的想法中有一个错误,因为我得到了值和索引长度之间的不匹配错误。我错过了什么?提前谢谢

我认为您需要创建一对
文件夹文件的
元组
,然后创建
数据帧

data = []
for folder in sorted(os.listdir('home')):
    for file in sorted(os.listdir('home/'+folder)):
        data.append((folder, file))

df = pd.DataFrame(data, columns=['Folder', 'File'])
print (df)
     Folder     File
0  a_folder   a_file
1  a_folder   b_file
2  a_folder   c_file
3  b_folder  aa_file
4  b_folder  bb_file
5  b_folder  cc_file
缺少a')括号df=pd.DataFrame(列=['Folder','File'])