如何解决 TypeError: can only concatenate str

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)

错误


======== 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


白衣染霜花
浏览 189回答 3
3回答

holdtom

在第 8 行使用,str(txt)因为你不能连接string和int如果您正在谈论创建文本文件,那么您应该使用".txt"而不是str(txt).

明月笑刀无情

你错过了 txt 的转换,所以将txt更改为str(txt):import ostxt = 1mmyyyy =&nbsp; ' -08-2020 'for f in range (1,1001):&nbsp; &nbsp; for i in range (1,11) :&nbsp; &nbsp; &nbsp; &nbsp; if not os.path.exists('C:\\Users\\Hayavadan\\OneDrive\\Python\\' + str(i)&nbsp; + mmyyyy):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;os.mkdir ("C:\\Users\\Hayavadan\OneDrive\Python\\" + str (i) + mmyyyy)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;open ("C:\\Users\\Hayavadan\\OneDrive\\Python\\1 -08-2020\\" + str(f) + str(txt) , "w")&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;os.rmdir ("C:\\Users\\Hayavadan\OneDrive\Python\\" + str (i) + mmyyyy)

忽然笑

您应该将 txt 转换为 string ".txt"。这里的代码:import ostxt = 1mmyyyy =&nbsp; ' -08-2020 'for f in range (1,1001):&nbsp; &nbsp; for i in range (1,11) :&nbsp; &nbsp; &nbsp; &nbsp; if not os.path.exists('C:\\Users\\Hayavadan\\OneDrive\\Python\\' + str(i)&nbsp; + mmyyyy):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;os.mkdir ("C:\\Users\\Hayavadan\OneDrive\Python\\" + str (i) + mmyyyy)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;open ("C:\\Users\\Hayavadan\\OneDrive\\Python\\1 -08-2020\\" + str(f) + ".txt" , "w")&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;os.rmdir ("C:\\Users\\Hayavadan\OneDrive\Python\\" + str (i) + mmyyyy)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python