user3582082
user3582082

Reputation: 31

Creating and naming files with a while function

i'm trying to create files, one for each day of the year, and I was thinking I would use while or for for this. but it doesn't seem to work since I'm mixing numbers and letters.

def CreateFile():
    date = 101 
#this is supposed to be 0101 (first of januar, but since i can't start with a 0 this had to be the other option)

    while date <= 131:
        name = (date)+'.txt'
        date += 1
CreateFile()

Upvotes: 1

Views: 44

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122159

You can't concatenate strings and integers:

name = date + '.txt' # TypeError

but you can use str.format to create the filename:

name = "{0}.txt".format(date)

Using str.format also allows you to force four digits, including the leading zero:

>>> "{0:04d}.txt".format(101)
'0101.txt'

(see the documentation for more on formatting options).

Finally, given that you know how many times you will loop, I would recommend a for loop with range here, to avoid initialising and incrementing date manually:

for date in range(101, 132):
    name = "{0:04d}.txt".format(date)
    ...

Upvotes: 2

Related Questions