All in one channel
All in one channel

Reputation: 23

How to solve the TypeError: can only concatenate str (not "int") to str error in python?

import os

txt = 1

mmyyyy =  ' -08-2020 '

for f in range (1,1001):

    for i in range (1,11) :

        if not os.path.exists('C:\\Users\\Hayavadan\\OneDrive\\Python\\' + str(i)  + mmyyyy):

             os.mkdir ("C:\\Users\\Hayavadan\OneDrive\Python\\" + str (i) + mmyyyy)

             open ("C:\\Users\\Hayavadan\\OneDrive\\Python\\1 -08-2020\\" + str(f) + txt , "w")

    else:
         os.rmdir ("C:\\Users\\Hayavadan\OneDrive\Python\\" + str (i) + mmyyyy)

The error

======== RESTART: C:/Users/Hayavadan/OneDrive/Python/delete by hayu 3.py =======
Traceback (most recent call last):
  File "C:/Users/Hayavadan/OneDrive/Python/delete by hayu 3.py", line 8, in <module>
    open ("C:\\Users\\Hayavadan\\OneDrive\\Python\\1 -08-2020\\" + str(f) + txt , "w")
TypeError: can only concatenate str (not "int") to str

Upvotes: 1

Views: 111

Answers (3)

Youness Saadna
Youness Saadna

Reputation: 812

Use str(txt) in the 8 line because you can't concatenatestring and int

If you are talking about creating a text file then you should use ".txt" instead of str(txt).

Upvotes: 1

Ricardo Rendich
Ricardo Rendich

Reputation: 651

You missed the cast for txt, so change txt to str(txt):

import os

txt = 1

mmyyyy =  ' -08-2020 '

for f in range (1,1001):

    for i in range (1,11) :

        if not os.path.exists('C:\\Users\\Hayavadan\\OneDrive\\Python\\' + str(i)  + mmyyyy):

             os.mkdir ("C:\\Users\\Hayavadan\OneDrive\Python\\" + str (i) + mmyyyy)

             open ("C:\\Users\\Hayavadan\\OneDrive\\Python\\1 -08-2020\\" + str(f) + str(txt) , "w")

    else:
         os.rmdir ("C:\\Users\\Hayavadan\OneDrive\Python\\" + str (i) + mmyyyy)

Upvotes: 0

Shmn
Shmn

Reputation: 703

You should convert txt to string ".txt". Here the code:

import os

txt = 1

mmyyyy =  ' -08-2020 '

for f in range (1,1001):

    for i in range (1,11) :

        if not os.path.exists('C:\\Users\\Hayavadan\\OneDrive\\Python\\' + str(i)  + mmyyyy):

             os.mkdir ("C:\\Users\\Hayavadan\OneDrive\Python\\" + str (i) + mmyyyy)

             open ("C:\\Users\\Hayavadan\\OneDrive\\Python\\1 -08-2020\\" + str(f) + ".txt" , "w")

    else:
         os.rmdir ("C:\\Users\\Hayavadan\OneDrive\Python\\" + str (i) + mmyyyy)

Upvotes: 0

Related Questions