Skip to content
Advertisement

Python variable file path and string prefixes

Using tkinter to select output folder for processed files.

root = tk.Tk()
root.withdraw()
file_output = filedialog.askdirectory()
x = "NAME"


file_output 
>>>'C:/Users/person/Documents/'

Would like to use file_output and x as variables for my file path, My attempt:

df.to_csv(f"{file_output}/{x} 6-30-22 11s & 12s.csv")

print((f"{file_output}/{x} 6-30-22 11s & 12s.csv"))
>>> C:/Users/person/Documents/NAME 6-30-22 11s & 12s.csv

This does not work in my program. The output I need is

C:\Users\person\Documents\NAME 6-30-22 11s & 12s.csv

I am reading the docs https://docs.python.org/3/reference/lexical_analysis.html#grammar-token-stringprefix

Still don’t understand how to escape or a workaround, Help would be much appreciated.

Advertisement

Answer

you can easily use replace to get the output you want, so try this:

df.to_csv((f"{file_output}/{x} 6-30-22 11s & 12s.csv").replace('/', '\\'))

print((f"{file_output}/{x} 6-30-22 11s & 12s.csv").replace('/', '\\'))

output:

C:\Users\person\Documents\NAME 6-30-22 11s & 12s.csv
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement