使用操作系统和Glob搜索和连接.csv文件,并使用Pandas创建DataFram

2024-07-01 07:14:01 发布

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

问题

我有多个目录,每个目录都有子目录。这些子目录包含包含数字数据的.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

我想要的行为

在dir1中找到一个.csv,在dir2中找到一个.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

必要时提问


Tags: 文件csv数据目录文件夹os数字out
1条回答
网友
1楼 · 发布于 2024-07-01 07:14:01

您可以使用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

相关问题 更多 >

    热门问题