我有一个脚本,它遍历子目录,并将.csv文件中的所有数据组合到一个大.csv文件中。但我想对其进行修改,以便为每个子目录创建一个单独的组合.csv(最好在子目录后命名)。到目前为止,我尝试过的一切似乎都无法做到。我想念什么?我的原始脚本如下。

datax = []
dirx = 'path/to/folder'
for dirs, subdirs, files in os.walk(dirx):
    for f in files:
        if f.endswith('.csv'):
            data2 = pd.read_csv(os.path.join(dirs, f), sep=' ', header=None, names=column_names)
            datax.append(data2)
frame = pd.concat(datax)
frame.to_csv('alldata.csv', sep=',', index=False)


如果将frame =行移到os.walk循环中,则表示没有任何内容可以串联。

最佳答案

我找到了一种解决方案,但它可能不是最漂亮的一种:

# Your path
dirx = path

# Dictionnary to put all your subdirs concatenates
dict_data = {}

for dirs, subdirs, files in os.walk(path):

    # First check if your subdirs is not empty
    if subdirs:

        # For every sudirs you have
        for i in subdirs:

            # I run a for loop inside of it
            for dirs2, subdirs2, files2 in os.walk(path + "\\"+ i):

                # I then instantiate a list
                list_data = []
                for j in files2:

                    # I append the data of your different files in this subdir to this list
                    data = pd.read_csv(path + "\\" + i + "\\" + j, sep=' ', header=None, names=column_names)

                    list_data.append(data)

                # Concatenate and store it in the dictionnary, so you have the data compartimented
                dict_data[i] = pd.concat(list_data)

dict_data[frame].to_csv('the/data/from/subdir/wanted', sep=',', index=False)


它应该给您这样的结果(testi,testa是我的子目录):

python - 将子目录中csv文件中的数据与Python合并-LMLPHP

希望对您有所帮助!

关于python - 将子目录中csv文件中的数据与Python合并,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54561053/

10-09 07:06