Home > OS >  Error in creating a file with variable name in python
Error in creating a file with variable name in python

Time:03-30

from datetime import datetime

time_today = datetime.now()
todayDate = time_today.strftime('%d/%m/%Y')
filename = "Attendance - "   todayDate
with open(f'{filename}.csv', 'w') as fp:
    fp.writelines(f'Name,Date,Time')

This is my code for creating a new file with a variable file name. When i use just filename="hello", it works and creates hello.csv but for filename = "Attendance - " todayDate it shows this error:

Traceback (most recent call last):
File "e:\College\Coding\SY\face-recog\file-create.py", line 6, in <module>
    with open(f'{filename}.csv', 'w') as fp:
FileNotFoundError: [Errno 2] No such file or directory: 'Attendance - 29/03/2022.csv'

CodePudding user response:

The slashes in todayDate are getting interpreted by python as a path.

You can probably escape them or the easier method would probably be to change them to dashes instead:

todayDate = time_today.strftime('%d-%m-%Y')

CodePudding user response:

This should fix the problem:

from datetime import datetime
    
    time_today = datetime.now()
    todayDate = time_today.strftime('%d/%m/%Y')
    filename = "Attendance - "   str(todayDate)
    with open(f'{filename}.csv', 'w') as fp:
        fp.writelines(f'Name,Date,Time')
  • Related