根据输入的文件类型,是否有办法将psv、csv或excel文件读入数据框?

2024-09-21 08:47:42 发布

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

我希望脚本的用户输入将被读入数据帧的文件路径和名称。 用户可以输入类似directory1\test1.csv或directory1\test1.psv或directory1\test1.xlsx的内容

无论他们输入的是psv、csv还是xlsx,我都希望通过以下逻辑将其读入数据帧:

如果文件名以.psv结尾,则df=pd.read\u psv(),elif文件名以.csv结尾,然后df=read\u csv(),elif文件名以.xlsx结尾,则df=pd.read\u excel()

有办法做到这一点吗


Tags: 文件csv数据用户脚本dfread文件名
1条回答
网友
1楼 · 发布于 2024-09-21 08:47:42

这就是我尝试过的:

#Specify the file directory where it is located
file_path = input("Enter file directory path:")

#Specify the file name where it is located
file_name = input("Enter file name:")

#number of rows to skip to read the column names
skip_rows = input("Skip n rows:")

input_file = file_path + file_name

if file_name.endswith('.csv'):
    df = pd.read_csv(input_file, skiprows = skip_rows)
elif file_name.endswith('.xlsx'):
    df = pd.read_excel(input_file, skiprows = skip_rows)
elif file_name.endswith('.psv'):
    df = pd.read_csv(input_file, sep = "|", skiprows = skip_rows)
else: 
    print('file format not supported')

相关问题 更多 >

    热门问题