将多个以字符串开头的csv文件读入python中的单独数据帧 [英] Read multiple csv files starting with a string into separate data frames in python

查看:62
本文介绍了将多个以字符串开头的csv文件读入python中的单独数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大约 500 个以字母T"开头的.csv"文件,例如'T50, T51, T52 ..... T550' 文件夹中还有一些其他的 ',csv' 文件,其中包含其他随机名称.我想读取所有以T"开头的 csv 文件并将它们存储在单独的数据帧中:'t50、t51、t52...等'

I have about 500 '.csv' files starting with letter 'T' e.g. 'T50, T51, T52 ..... T550' and there are some other ',csv' files with other random names in the folder. I want to read all csv files starting with "T" and store them in separate dataframes: 't50, t51, t52... etc.'

我写的代码只是将这些文件读入数据帧

The code I have written just reads these files into a dataframe

import glob
import pandas as pd

for file in glob.glob("T*.csv"):
    print (file)

我想为每个数据框使用不同的名称 - 最好是它们自己的文件名.我怎样才能在它的for 循环"中实现这一点?

I want to have a different name for each dataframe - preferably, their own file names. How can I achieve this within its 'for loop'?

推荐答案

完全同意@Comos
但如果您仍然需要单独的变量名称,我调整了这里的解决方案!

Totally agree with @Comos
But if you still need individual variable names, I adapted the solution from here!

import pandas as pd
import os

folder = '/path/to/my/inputfolder'

filelist = [file for file in os.listdir(folder) if file.startswith('T')]
for file in filelist:
    exec("%s = pd.read_csv('%s')" % (file.split('.')[0], os.path.join(folder,file)))

这篇关于将多个以字符串开头的csv文件读入python中的单独数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆