1

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()

1 Answer 1

2

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)
    ...
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, that went fast. Canged it to what you said and now it works great. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.