Python Forum
String to File Path - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: String to File Path (/thread-25645.html)



String to File Path - creedX - Apr-06-2020

I am trying to create a file path from a string using os.path.normpath, however, I need a double \ at the beginning and this function doesn't allow this (from what I understand). Inside the pd.read_excel function I need the following: r'\\srpx\Folder\Data.xls'

Here is the code that is not working:

import os
import pandas as pd

excel_string = str("r'\\srpx\Folder\Data.xls'")
excel_file = os.path.normpath(excel_string)

pd.read_excel(excel_file)
By the way, this works perfectly:

pd.read_excel(r'\\srpx\Folder\Data.xls')



RE: String to File Path - buran - Apr-06-2020

why do you add str(" and ")?


RE: String to File Path - creedX - Apr-06-2020

I probably oversimplified my problem. What I really want is to use a variable to define the folder name. I think to change up the "Folder" piece of the file path everything needs to be a string. I am not sure if there is another way to go about using a variable in a file path.

This is what I really want:

import os
import pandas as pd

folder_name = "Folder"
excel_string = str("r'\\srpx\") + folder_name + str("\Data.xls'")
excel_file = os.path.normpath(excel_string)
 
pd.read_excel(excel_file)



RE: String to File Path - buran - Apr-06-2020

you keep doing the same
the idea of r in front of string is that it's a raw string. But you enclose it in double quotes and make it useless as path
also ne need to use str() because everything you have is already a str.
Finally, the best is to use os.path.join()


>>> folder_name = 'some_folder'
>>> os.path.join(r'\\sprx', folder_name, 'Data.xls')
'\\\\sprx/some_folder/Data.xls'
and before you ask - \\\\ are actually 2 escaped backslahes


RE: String to File Path - creedX - Apr-06-2020

This worked great. Thanks so much!