How can I add a date to a literal file path in Python

Hello,

I’m trying to add a script to a button to export a table to csv when the button is clicked. The filename should be a timestamp. I’ve added the following to a button script:

# Create a variable that references our Power Table. You could modify this part
# of the example to point to a different component in the window.
component = event.source.parent.getComponent('Table')
timestamp = system.date.now()
# Use system.dataset.toCSV to turn the dataset into a CSV string
csv = system.dataset.toCSV(component.data)

filepath = "C:\myExports\"  
#I've also tried "C:\\myExports\\" this has no change, if I use r"C:\myExports\" it generates an error
timestampSTR = str(timestamp)
filetype = ".csv"
filestring = filepath+timestampSTR+filetype

# Write to local file system. Note the "r" character right before the directory path.
# This denotes a raw string literal, meaning we ignore escape sequences (like the "/") r"C:\myExports\myExport.csv"
system.file.writeFile(filestring, csv)

I’m getting an error since the file path is showing up with double slashes instead of single.I know that you can use “r” before the string to make it literal, but how would I use it in this case?

Thanks,

I’d say it’s an error in your date format, though use of forward slashes is more ‘pythonic’.

timestamp = system.date.format(system.date.now(), 'YYYY-MM-dd_HH_mm_ss')

filepath = 'C:/myExports/{}.csv'.format(timestamp)

print filepath
>>> 
C:/myExports/2022-02-10_14_09_28.csv
>>> 
1 Like

Thank you, That worked!

# Create a variable that references our Power Table. You could modify this part
# of the example to point to a different component in the window.
component = event.source.parent.getComponent('Table')

# Use system.dataset.toCSV to turn the dataset into a CSV string
csv = system.dataset.toCSV(component.data)

timestamp = system.date.format(system.date.now(), 'YYYY-MM-dd_HH_mm_ss')

filepath = 'C:/myExports/{}.csv'.format(timestamp)

# Write to local file system. Note the "r" character right before the directory path.
# This denotes a raw string literal, meaning we ignore escape sequences (like the "/") r"C:\myExports\myExport.csv"
system.file.writeFile(filepath, csv)

Glad it worked for you. It’s because colons are not allowed in file names.
image

Caution: YYYY will give you a “weekyear”, which may not be what you want on the first or last week of the year. yyyy will give you the calendar year, which is probably the intention.

6 Likes

Force of habit as that’s almost always my use case. :laughing:

1 Like