victor
victor

Reputation: 5

Python: Formatting file paths with a variable filename

I used r' in front of the string so that Python doesn't treat the backslashes as escape sequences.

df.to_excel(r'C:\Users\A\Desktop\Data\file.xlsx', index = False) #exporting to excelfile named "file.xlsx"

However, this time I need the filename to be a variable instead. I usually format it by using F-string but I can't combine the r' and f' together. It doesn't work

df.to_excel(r'f'C:\Users\A\Desktop\Data\{filename}.xlsx'', index = False) 

How can i solve this? Thanks

Upvotes: 0

Views: 2363

Answers (3)

theimpulson
theimpulson

Reputation: 101

I would suggest using either pathlib or os.path module in case you are working with paths and want your project to be compatible with different OS.

For pathlib, you can use the following snippet. Note that the forward slashes will be automatically converted in the correct kind of slash for the current OS.

from pathlib import Path

data_folder = Path("C:/Users/A/Desktop/Data/")
file_name = 'myname.xlsx'
file_path = data_folder / file_name

df.to_excel(file_path, index = False) 

The answer to your current question would be using string concatenation. Something like this:

df.to_excel(r'C:\Users\A\Desktop\Data\' + f'{filename}.xlsx', index = False) 

Upvotes: 2

Shan S
Shan S

Reputation: 678

You don't have to place each within quote marks- 1 set will do:

fr'C:\Users\A\Desktop\Data\{filename}.xlsx'

Upvotes: 1

pjk
pjk

Reputation: 556

Quotes are wrong. You can use it like this.

df.to_excel(rf'C:\Users\A\Desktop\Data\{filename}.xlsx', index = False) 

Upvotes: 1

Related Questions