Search code examples
pythonstringtkinterxlrd

Raw String Python Alternative?


I am trying to read in an excel file using xlrd and use tkinter to find the file. I am having trouble with the \ operator. If I would hard code the file path I could use the raw string command, r'filepath'. Is there something similar I could use, like, r(filepath) to convert the string to a raw string? My code and the error is listed below,

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)

Error:

File "C:\Program Files\Anaconda3\lib\site-packages\xlrd__init__.py", line 395, in open_workbook with open(filename, "rb") as f: FileNotFoundError: [Errno 2] No such file or directory: "('filepath',)"


Solution

  • There is no such thing as a raw-string within a running Python interpreter. raw-strings are only useful for written Python-Code to make it easier for programmers to enter otherwise escaped characters - most notably back-slashes that are also used in regular expressions as escape characters themselves.

    Your problem is different: you think you get a path from askopenfilename. But what you get is a tuple with a number of paths, in your case just one.

    So just use tkinter.filedialog.askopenfilename without the trailing s to get just one.