0

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

1
  • 2
    Your quotes are incorrect, try rf'C:\Users\A\Desktop\Data\{filename}.xlsx' Commented Jun 30, 2020 at 14:23

3 Answers 3

2

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) 
Sign up to request clarification or add additional context in comments.

Comments

1

Quotes are wrong. You can use it like this.

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

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.