Search code examples
pythonpython-3.xf-string

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

Solution

  • 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