【问题标题】:Can I define file path and file name before importing a file (python)?我可以在导入文件(python)之前定义文件路径和文件名吗?
【发布时间】:2022-01-06 20:30:22
【问题描述】:

我正在尝试使用 pd.read_excel 将具有多个工作表的 excel 文件导入 python。 我可以预先定义文件路径和excel文件名吗?这将使为具有不同文件路径和 excel 文件名的不同数据集运行脚本变得更加容易。 我尝试了类似的方法,但没有奏效:

#Define file path
file_path ="copied and pasted actual file path here"
#Define raw data excel sheet name
raw_data="copied and paste excel file name here"

#import excel 
import pandas as pd

PL_raw_data = pd.read_excel (r'"file_path"/"raw_data".xlsx',sheet_name='copied and pasted excel sheet name here')

提前致谢!

【问题讨论】:

  • 这能回答你的问题吗? How to insert string into a string as a variable?
  • 这是典型的how to use a variable question。由于您使用路径的方式,可能会出现一些复杂性。但是,将其存储在变量中与不将其存储在变量中应该没有区别。您的问题在于您传递字符串的方式。 r-literal 使得一切都是原始的(因此引号保留在字符串中)。您想连接字符串,或者更好地在其他地方使用 f-strings 并简单地引用变量。

标签: python excel pandas file


【解决方案1】:

试试这个

#Define file path
file_path ="copied and pasted actual file path here"
#Define raw data excel sheet name
raw_data="copied and paste excel file name here"

#import excel 
import pandas as pd

PL_raw_data = pd.read_excel (file_path + raw_data, sheet_name='copied and pasted excel sheet name here')

【讨论】:

    猜你喜欢
    • 2018-09-29
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多