如何使用python读取文件夹中同名的成对csv和json文件?

7jmck4yq  于 2022-12-06  发布在  Python
关注(0)|答案(3)|浏览(148)

考虑我的文件夹结构有这些方式的文件:-

abc.csv
abc.json
bcd.csv
bcd.json
efg.csv
efg.json

等等,即一对csv文件和json文件具有相同的名称,我必须通过阅读相同名称的文件来执行相同的操作,做一些操作,然后继续下一对文件。我该怎么做呢?基本上我心目中的伪代码是:-

for files in folder_name:
    df_csv=pd.read_csv('abc.csv')
    df_json=pd.read_json('abc.json')
    # some script to execute
    #now read the next pair and repeat for all files
a2mppw5e

a2mppw5e1#

你有没有想过这样的事?

import os

# collects filenames in the folder
filelist = os.listdir()
# iterates through filenames in the folder
for file in filelist:
# pairs the .csv files with the .json files
    if file.endswith(".csv"):
        with open(file) as csv_file:
            pre, ext = os.path.splitext(file)
            secondfile = pre + ".json"
            with open(secondfile) as json_file:
                # do something
nimxete2

nimxete22#

您可以使用glob模块提取与模式匹配的文件名:

import glob
import os.path

for csvfile in glob.iglob('*.csv'):
    jsonfile = csvfile[:-3] + 'json'
    # optionaly control file existence
    if not os.path.exists(jsonfile):
        # show error message
        ...
        continue
    # do smth. with csvfile
    # do smth. else with jsonfile
    # and proceed to next pair
6l7fqoea

6l7fqoea3#

如果目录结构一致,您可以执行以下操作:

import os

for f_name in {x.split('.')[0] for x in os.listdir('./path/to/dir')}:
    df_csv = pd.read_csv("{f_name}.csv")
    df_json = pd.read_json("{f_name}.json")
    # execute the rest

相关问题