I am trying to accept a path from a user, and then load the spreadsheet at that path:
df_path = input('What is the file path?')
df = pd.read_csv(df_path, index_col=2)
Some users, when pasting their paths in, are told it is invalid, because of escape sequences. Here, \166
is being converted to v
:
df_path = input('What is the file path?')
C:\Data\166 - data\data.csv #entered by user
df = pd.read_csv(df_path, index_col=2)
FileNotFoundError: [Errno 2] No such file or directory: "C:\\Datav - data\\data.csv"
I'm aware that manually loading the path within the code, this can be accounted for:
dataset = pd.read_csv(r"C:\Data\166 - data\data.csv", index_col=2)
However, I can't find a way to make this work while accepting user input and storing it as a variable (tried many ways of attempting to do so, one example here):
df_path = input('What is the file path?')
"C:\Data\166 - data\data.csv" #entered by user
df = pd.read_csv("r'" + df_path, index_col=2)
OSError: [Errno 22] Invalid argument: "r'C:\\Datav - data\\data.csv"
It also doesn't work to try to rewrite the path, replacing \
with \\
:
df_path = df_path.replace("\", "\\")
SyntaxError: unexpected character after line continuation character
-
df_path = df_path.replace(r"\", r"\\")
SyntaxError: unexpected character after line continuation character
How can this be done?