首页 > 解决方案 > 如何读取多个文件然后连接:我具有检查文件是否存在并读取是否存在的功能,连接时面临问题

问题描述

5 个不同的文件夹中有 5 个文件,我编写了一个函数来检查文件是否存在并读取文件并存储在数据框中。我有连接函数说 pd.concat(file1,file2,file3,file,4,file5)。问题:不是每次我们都得到所有 5 个文件,很少我只得到 4 个文件,函数会读取文件,但问题在于连接。例如:文件 2 不存在,它给我错误文件 2 未定义。

代码 :

for x in f:
    if x.startswith("File_A1"):
        mypath = os.path.join(root,'A1','ABB','BGH',x)
        A1 = pd.read_csv(mypath, delimiter="|",header = 1)
        A1['GROUP']= 'A1'
        A1.loc[A1['coms'] == "ASIA"]
        A1.drop_duplicates(inplace = True)


    elif x.startswith("File_A2"):
        mypath = os.path.join(root,'A2','ABB','BGH',x)
        A2 = pd.read_csv(mypath,delimiter="|",header = 1)
        A2['GROUP']= 'A2'
        A2.loc[A2['coms'] == "ASIA"]
        A2.drop_duplicates(inplace = True)

    elif x.startswith("File_A3"):
        mypath = os.path.join(root,'A3','ABB','BGH',x)
        A3 = pd.read_csv(mypath,delimiter="|",header = 1)
        A3['GROUP']= 'A3'
        A3.loc[A3['coms'] == "ASIA"]
        A3.drop_duplicates(inplace = True)



df = pd.concat([A1,A2,A3])

标签: python-3.xpandascsv

解决方案


我认为最好的方法是通过以下方式创建 DataFrames 列表append

编辑:您可以按文件名的开头列表循环,并A1通过以下A2方式动态创建start.split('_')[1]

dfs = []
for x in f:
    starts = ["File_A1", "File_A2", "File_A3"]
    for start in starts:
        if x.startswith(start):
            mypath = os.path.join(root,start.split('_')[1],'ABB','BGH',x)
            df = pd.read_csv(mypath, delimiter="|",header = 1)
            df['GROUP']= start.split('_')[1]
            df.loc[df['coms'] == "ASIA"]
            df.drop_duplicates(inplace = True)
            dfs.append(df)

df = pd.concat(dfs, ignore_index=True)

推荐阅读