Reputation: 1696
I am working on a code that takes the path of a file and the reads it. The code is,
import sys
import os
user_input = input("Enter the path of your file: ")
assert os.path.exists(user_input), "I did not find the file at, "+str(user_input)
However, I am on a Windows machine in which, the path names come with a \
, like, C:\your\path\and\file.xlsx
Each time I enter the file name to the prompt, I need to manually replace all \
with /
and then run the code.
Is there a solution such that I enter C:\your\path\and\file.xlsx
but the code takes it as, C:/your/path/and/file.xlsx
Regards.
Upvotes: 1
Views: 2151
Reputation: 5108
Use pythons builtin pathlib
like this:
from pathlib import Path
# No matter what slash you use in the input path
# I used Raw-Prefix 'r' here because \t would otherwise be interpreted as tab
path_a = Path(r"C:\Temp\test.txt)
path_b = Path(r"C:\Temp/test.txt)
path_c = Path(r"C:/Temp/test.txt)
path_d = Path(r"C:\\Temp\\test.txt)
print(path_a, path_b, path_c, path_d)
# all Paths will be the same:
# out >> C:\Temp\test.txt C:\Temp\test.txt C:\Temp\test.txt C:\Temp\test.txt
Furthermore you can also easily extend a given Path like this:
path_e = Path("C:\Temp")
extended_path = path_e / "Test"
print(extended_path)
# out >> C:\Temp\Test
So in your case simply do it like this:
import sys
import os
from pathlib import Path
user_input = input("Enter the path of your file: ")
file_path = Path(user_input)
if not os.path.exists(file_input):
print("I did not find the file at, " + str(file_path))
Upvotes: 3
Reputation: 5274
Oddly enough, when I use \
in my path it just worked. But for whatever reason if yours is not, here is a way to change backslash to slash. One with a regex and one using replace:
import sys
import os
import re
user_input = input("Enter the path of your file: ")
#with a regex
user_input_regex = re.sub(r"\\", "/", user_input)
print(user_input_regex)
#using replace
user_input_replace = user_input.replace("\\","/")
print(user_input_replace)
I believe that replace is slightly faster but if you want to change other stuff (or just like using regex) the regex will probably offer more options down the road. The key to this is the \
needs to be escaped with a \
since itself is an escape character.
Upvotes: 1