Pandas reading csv files with partial wildcard

后端 未结 4 1717
天涯浪人
天涯浪人 2021-01-05 13:45

I\'m trying to write a script that imports a file, then does something with the file and outputs the result into another file.

df = pd.read_csv(\'somefile2018.

4条回答
  •  -上瘾入骨i
    2021-01-05 14:40

    To read all of the files that follow a certain pattern, so long as they share the same schema, use this function:

    import glob
    import pandas as pd
    
    def pd_read_pattern(pattern):
        files = glob.glob(pattern)
    
        df = pd.DataFrame()
        for f in files:
            df = df.append(pd.read_csv(f))
    
        return df.reset_index(drop=True)
    
    df = pd_read_pattern('somefile*.csv')
    
    

    This will work with either an absolute or relative path.

提交回复
热议问题