如何显示pandas read_csv()函数读取的csv文件名?

2024-06-28 19:59:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想显示pandas.read\u csv()函数读取的csv文件名。我尝试了以下代码,但无法显示csv文件名

import pandas as pd 
df=pd.read_csv("abc.csv") 
print(df.info())

我想显示“abc”。为我的处境指引方向。提前谢谢


Tags: csv函数代码importinfopandasdfread
3条回答

You can use something like this as read_csv does not save the file_name.

Using glob will give you the ability to put wildcards or regex for all the CSV files on that folder for reading.

import glob

data = {}
for filename in glob.glob("/path/of/the/csv/files/*.csv"):
    data[filename.split("/")[-1].split(".")[0]] = pd.read_csv(filename)

for key, value in data.items():
    print(key)
    print(value.info())
    print("\n\n")

filename.split("/")[-1].split('.')[0]

The above line may look complicated but it just split the file_name 2 times.

使用pandasread_csv函数时,会得到一个不包含文件名的数据帧。因此,解决方案是将.csv的名称存储在变量中,然后打印它。您可以在pandas.DataFrame Documentation中检查熊猫数据帧

import pandas as pd 
name = "abc.csv"
df=pd.read_csv(name) 
print(name.split(".")[0])

pandas.read_csv()方法接受File对象(实际上是任何具有read()方法的类似文件的对象)

并且File类有一个name对象,该对象具有打开的文件的名称

我认为这段代码和情况完全没有意义,因为您事先已经知道文件名,但为了完整起见,现在开始:

import pandas as pd

csv_file = open("your_csv_filename.csv")
print(csv_file.name)
df = pd.read_csv(csv_file)

相关问题 更多 >