问题
我有多个目录,每个目录都有子目录。这些子目录包含.csv文件,其中包含数字数据。我想让我们glob和os(不是shell脚本)搜索两个指定的目录,然后找到特定的文件夹并以下面将要描述的格式将它们连接起来。
dir1 contains subdir1 contains A.csv
contains subdir2 contains B.csv
dir2 contains subdir1 contains A.csv
contains subdir2 contains B.csv
在两种情况下
>>> cat A.csv
1
2
3
4
5
>>> cat B.csv
6
7
8
9
10
我想要的行为
在目录1中找到A.csv,在目录2中找到A.csv,搜索每个文件夹和目录,然后合并它们。合并后,创建pandas.DataFrame
>>> python3 merge.py dir1 dir2 A.csv
# prints df created from out.csv
x y
0 1 1
1 2 2
2 3 3
3 4 4
4 5 5
>>> cat out.csv
1
2
3
4
5
1
2
3
4
5
如有需要,请提问
您可以使用os.walk
浏览目录,并使用glob.glob
搜索* .csv文件,如下所示:
from os import walk
from os.path import join
from glob import glob
root_dir = '/some/path/to_a_directory/'
for rootdir, _, _ in walk(root_dir):
all_csv = glob(join(root_dir, '*.csv'))
for fpath in all_csv:
# Open the file and do something with it