Serdia
Serdia

Reputation: 4418

How to use f string in a path location

I simply want to use filename variable in my f sting. What am I missing here?

# generating file name
filename = 'AG' + datetime.date.today().strftime("%m%d%Y")

# saving file
df.to_csv(f'C:\Users\username\Documents\folder1\folder2\{filename}.csv', index=False, sep=',')

Error:

    df.to_csv(f'C:\Users\username\Documents\folder1\folder2\{filename}.csv', index=False, sep=',')
              ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

Upvotes: 1

Views: 23588

Answers (2)

dawg
dawg

Reputation: 103774

As tiega mentioned, the issue you are having is with the \ in constructing the f string.

As a more solid approach, you may consider using pathlib to manipulate paths.

Examples:

import datetime 
from pathlib import Path, PureWindowsPath

filename = 'AG' + datetime.date.today().strftime("%m%d%Y")
fp=Path(r'C:/Users/username/Documents/folder1/folder2', filename+'.csv')
# you could actually use this unmodified to open the file on Windows...

print(PureWindowsPath(fp))
# show the Windows presentation of that path
# C:Users\username\Documents\folder1\folder2\AG05072020.csv

Upvotes: 2

user12734467
user12734467

Reputation:

The problem is with backslashes in the string, not with fstring formatting. You need to escape the back slashes in your Windows style path by using \\, because a single backslash indicates an escape character, for example \n for a newline character and \t for a tab.

As @dawg mentioned, you can also combine f with the r raw-string so python doesn't escape any characters.

Upvotes: 2

Related Questions