【问题标题】:Is there a way to read either a psv, csv or excel file into a dataframe depending on the file type of the input?有没有办法根据输入的文件类型将 psv、csv 或 excel 文件读入数据框?
【发布时间】:2020-04-17 00:29:04
【问题描述】:

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

无论他们输入的是 psv、csv 还是 xlsx,我都想将其读入具有以下逻辑的数据帧:

如果文件名以 .psv 结尾,则 df = pd.read_psv(),elif 文件名以 .csv 结尾,然后 df = read_csv(),elif 文件名以 .xlsx 结尾,然后 df = pd.read_excel()。

有没有办法做到这一点?

【问题讨论】:

  • 是的。如果您表现出诚实的尝试,您可以在这里获得更多帮助 :-) 您当前的逻辑看起来不错,您应该能够通过filename.lower().endswith(...) 满足您的要求
  • 这里可以使用.endswith()字符串方法。除此之外,请提供您迄今为止根据自己的研究所做的尝试,以及您的努力结果

标签: python python-3.x pandas dataframe


【解决方案1】:

当然有。

import os

# Get the file extension
ext = os.path.splitext(in_file)[1]

if ext == '.psv':
    df = pd.read_psv(in_file)
elif ext == '.csv':
    df = pd.read_csv(in_file)
elif ext == '.xlsx':
    df = pd.read_excel(in_file)
else:
    raise RuntimeError('File extension not recognized')

【讨论】:

    【解决方案2】:

    这是我尝试过的:

    #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')
    

    【讨论】:

      猜你喜欢
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多