首页 > 解决方案 > 如何通过将文件位置作为输入来导入 Excel 工作表(使用 Pandas)

问题描述

我正在努力学习熊猫。我通常使用以下方法导入 excel 表:

import pandas as pd
df = pd.read_excel (r'C:\Users\Comp\Documents\filename.xlsx')

但我希望让用户自己输入文件位置。我尝试将文件位置作为输入并使用格式选项,但它并没有真正适合我。这是我尝试过的:

print("Do you have another sheet for a new DF?")
ch = input("Press Y or N")
if ch =="Y":
    df2 = pd.read_excel (r'{}'.format(input("copy and paste the location of the excel file here ")))
     
我只是在这里进行试运行,看看它是否有效。这是我得到的错误:[Errno 22] Invalid argument: '\u202aC:\Users\Ashu\Documents\Book1.xlsx'

请让我知道如何完成这项任务。谢谢 :)

标签: pythonpandas

解决方案


以下是一些信息: 从 Python 字符串中删除 u202a

您可以执行以下操作:

print("Do you have another sheet for a new DF?")
ch = input("Press y or n")

if ch =="y":
    filePath = input("copy and paste the location of the excel file here ")
    filePath = filePath.strip("‪u202a")
    df2 = pd.read_excel (r'{}'.format(filePath))

推荐阅读