I am writing a script which prompts the user to input a file path. The user might be working on a mac or a windows PC and I want the user to just copy the file path and paste it when asked.
Right-clicking a file on a mac or shift+right-clicking a file in windows give the option to copy its path. Copying the file path on a mac gives it with forward slashes, while in windows the path has backslashes.
Hence, I am trying to get the work done with the user operating in the same way and do the least of the work (just copy and past), regardless whether the user works in macos or windows.
So far, I had this working on a mac:
import pandas as pd
import sys
while True:
path_to_file=input("Pass the file path: ") #I suppose I must do something here so that python can see a file path
try:
file=pd.read_excel(path_to_file)
break
except FileNotFoundError:
print('\n\tSorry, the file is not found.')
sys.exit()
print("Your dataset looks like this\n")
print(file.head(3))
But, for windows, I can't seem to be able to work around with os
and pathlib
that I found in other posts, so that the input string is actually recognized as a file path.
I, then, tried to add the following piece of code before the try
which apparently did not work:
if "\\" in path_to_file: #it will print the file path with two backslashes and this is why I used \\
path_to_file=path_to_file.replace("\\", "/")
Any advice how to overcome this please?
It has been some time since I posted this question but the code that has worked for me goes as follows:
import os
filepath= os.path.normcase('path_with_either_\_or/')
This way, I can work with a script in any environment and share the script with any user.
When I work on a mac, I apply a right-click on the file of interest and I select "Copy path" > "POSIX path" and the path is populated with a forward slash " / ".
When I work in a Windows environment, I apply a Shift+right-click on the file of interest and I select "Copy as path" and the path is populated is with backslash " \ ".