Search code examples
pythonstringpandasformatioerror

Formatting a string in Python is giving me a file not found error


I am new to python and trying to work with Pandas to do some work with several .csv files that have predictable names, Log_(yyyy/mm/dd).

What I'm planning is simple enough, but opening the file is giving me problems.

today = date.today()
m,d,y = today.month, today.day, today.year

file_name = 'Log_{}-{}-{}'.format(y,m,d)
pd.read_csv(file_name)

This will give me an error, but this works

file_name = 'Log_2015-01-10'
pd.read_csv(file_name)

They print the same thing, and str(file_name) doesn't fix the issue.


Solution

  • You have two problems: your tuple assignment swaps the day and year values, and you need to zero-pad values below 10. You are actually producing the string 'Log_10-1-2015', not 'Log_2014-01-10'.

    Formatting a date into a string is easiest done by leaving formatting to the date object rather than extracting the individual components yourself:

    today = date.today()
    file_name = 'Log_{:%Y-%m-%d}'.format(today)
    

    The % fields are strftime() formatting instructions that use zero-padding by default.

    Demo:

    >>> from datetime import date
    >>> today = date.today()
    >>> 'Log_{:%Y-%m-%d}'.format(today)
    'Log_2015-01-11'
    

    Yes, it is already the 11th in my timezone. :-)