原始字符串 Python 替代方案?

Raw String Python Alternative?

我正在尝试使用 xlrd 读取 excel 文件并使用 tkinter 查找该文件。我在使用 \ 运算符时遇到了问题。如果我对文件路径进行硬编码,我可以使用原始字符串命令 r'filepath'。有没有类似的东西我可以使用,比如 r(filepath) 将字符串转换为原始字符串?下面列出了我的代码和错误,

import xlrd
from tkinter import Tk, filedialog, messagebox

application_window = Tk()
application_window.withdraw()

messagebox.showinfo("Information", "Select the Layout")
path = filedialog.askopenfilenames(title="Layout")

Layout = xlrd.open_workbook(path)

错误:

File "C:\Program Files\Anaconda3\lib\site-packages\xlrd__init__.py",第 395 行,在 open_workbook with open(filename, "rb") as f: FileNotFoundError:[Errno 2] 没有这样的文件或目录:“('filepath',)”

运行 Python 解释器中没有原始字符串这样的东西。原始字符串仅对编写的 Python-代码有用,使程序员更容易输入其他转义字符 - 最值得注意的是反斜杠,它们本身也在正则表达式中用作转义字符。

你的问题是不同的:你认为你从 askopenfilename 得到了一个路径。但是你得到的是一个 tuple 有很多路径,在你的例子中只有一个。

因此只需使用 tkinter.filedialog.askopenfilename 不带尾随的 s 即可得到一个。