将当前工作目录中的所有CSV文件读入具有正确文件名的熊猫

将当前工作目录中的所有CSV文件读入具有正确文件名的熊猫,csv,pandas,for-loop,Csv,Pandas,For Loop,我尝试使用一个循环来读取多个CSV(目前,但将来会混合使用该循环和xls) 我希望pandas中的每个数据帧都是相同的名称,不包括我文件夹中的文件扩展名 import os import pandas as pd files = filter(os.path.isfile, os.listdir( os.curdir ) ) files # this shows a list of the files that I want to use/have in my directory- t

我尝试使用一个循环来读取多个CSV(目前,但将来会混合使用该循环和xls)

我希望pandas中的每个数据帧都是相同的名称,不包括我文件夹中的文件扩展名

import os 
import pandas as pd


files = filter(os.path.isfile, os.listdir( os.curdir ) )
files #   this shows a list of the files that I want to use/have in my directory- they are all CSVs if that matters

# i want to load these into pandas data frames with the corresponding filenames

 # not sure if this is the right approach....
 # but what is wrong is the variable is named 'weather_today.csv'... i need to drop the .csv or .xlsx or whatever it might be

for each_file in files:
    frame = pd.read_csv( each_file)
    each_file = frame
伯尼看起来很棒,但有一个问题:

or each_file in files:
    frame = pd.read_csv(each_file)
    filename_only = os.path.splitext(each_file)[0]
   # Right below I am assigning my looped data frame the literal variable name of "filename_only" rather than the value that filename_only represents
   #rather than what happens if I print(filename_only)
    filename_only = frame
例如,如果我的两个文件是weather_today,即我的文件列表中的地震.csv(按该顺序),则不会同时创建“地震”和“天气”

但是,如果我只需键入'filename_only'并在python中单击enter键,那么我将看到地震数据帧。如果我有100个文件,那么列表循环中的最后一个数据帧名称将标题为“仅文件名”,而其他99个不会,因为以前的分配从未进行过,第100个将覆盖它们。

您可以使用此选项“将路径名路径拆分为一对(根,外部)这样,root+ext==path,ext为空或以句点开头,最多包含一个句点。“

如评论中所述,我们希望找到一种仅过滤CSV文件的方法,以便您可以执行以下操作:

files = [file for file in os.listdir( os.curdir ) if file.endswith(".csv")]

使用字典存储帧:

frames = {}

for each_file in files:
    frames[os.path.splitext(each_file)[0]] = pd.read_csv(each_file)
现在,您可以通过以下方式获得所选的数据帧:

frames[filename_without_ext]

很简单,对吧?不过要注意RAM的使用,读取大量文件可能会很快填满系统内存并导致崩溃

哇,很简单。如果您不介意在我的第一部分中询问-files=filter(os.path.isfile,os.listdir(os.curdir))----是否有方法将其指定为特定扩展名。我对这类事情还不熟悉……您所做的不只是用数据帧覆盖存储在
filename\u中的文件名吗?它将在循环的下一次运行中被覆盖。有点不明白这有什么意义。我又试了一次,但似乎不起作用。我想这是我第一次用csv读到它们。我重新启动了我的会话,我仍然以“today\u weather.csv”的名称而不是today\u weather.csv的名称获取所有文件。是的,但是为什么这样做有效,而上面的方法不起作用?当我尝试使用上面的中间打印步骤时,我得到了一个名称,但上面答案的最后部分似乎与作业不匹配。。。我还想把它们加载到内存中,而不是列表中。它是一个字典,而不是列表。这两者之间有很大的区别。你确定@bernie答案中的代码复制正确了吗?你所要求的不能严格执行。除非程序编写代码然后执行,否则不能声明变量。无法在Python中修改正在执行的代码。你唯一能做的就是修改你的变量。字典允许使用命名键,并向其附加值。这就是我的答案,这是回答问题的最简单方式。好的,我理解这一部分,但我相信问题出在单词FILENAME\u ONLY被用作变量aka“FILENAME\u ONLY”的拼写=weather\u data.csv,而不是仅“携带”拼写weather\u数据提取的文件名,从而设置weather\u data=weather\u data.csv你在绕着我转!让代码说话。你能用@bernie的答案和输出以及预期输出编辑你的问题吗?那将非常有帮助。
frames[filename_without_ext]