user7799242
user7799242

Reputation:

Creating a new file using a variable in python

The code that I am currently using is this:

date = time.strftime("%d/%m/%y")
filename = ('attendence{}' + str(date) +'.txt')
f = open(filename, 'w+')

However, the error I receive is this:

FileNotFoundError: [Errno 2] No such file or directory: 'attendence{}31/03/17.txt'

The error is not with other parts of my code as this will work.

f = open('attendence{}.txt', 'w+')

my end goal is to create a new file that contains the current date.

Upvotes: 1

Views: 52

Answers (1)

Eric Duminil
Eric Duminil

Reputation: 54233

The problem is with the date format :

date = time.strftime("%d/%m/%y")

You could try :

date = time.strftime("%d_%m_%y")

'attendence{}31/03/17.txt' isn't just a filename, it's a relative path with :

  • 1 folder : 'attendence{}31'
  • 1 subfolder : '03'
  • 1 filename '17.txt'.

Python is complaining that the folder 'attendence{}31/03' doesn't exist.

Note that {} might confuse the system, some programs or some users. If there's no information inside the curly brackets, you might as well remove them.

Upvotes: 1

Related Questions