Python类型错误:使用witn open()时设置字符串格式

Python类型错误:使用witn open()时设置字符串格式,python,Python,我有一个列表img_list和type chapter都是string,当我使用string formatiling in with open创建.jpg文件时,它显示TypeError 所以我做了一些测试,结果如下: 打印“/%s/%s/%d.jpg”%title,chapter,n并输出正确的结果 打开“/%s/%s/%d.jpg”和“wb”%title,chapter,n会导致TypeError,但实际上与1相同 打开'/%s/%s/'+strn+'.jpg'、'wb'%title',章节

我有一个列表img_list和type chapter都是string,当我使用string formatiling in with open创建.jpg文件时,它显示TypeError

所以我做了一些测试,结果如下:

打印“/%s/%s/%d.jpg”%title,chapter,n并输出正确的结果

打开“/%s/%s/%d.jpg”和“wb”%title,chapter,n会导致TypeError,但实际上与1相同

打开'/%s/%s/'+strn+'.jpg'、'wb'%title',章节为f时仍会导致类型错误 使用opendir+strn+'.jpg',wb'作为f:最后我将dir设置为'/%s/%s/'%title',然后它通过了 我真的很困惑这4种表达方式,为什么1和4是正确的,而2和3是不正确的

以下是代码:

dir='./%s/%s/' %(title,chapter)
    n=0
    for i in img_list:
        n+=1
        '''1.this is correct'''
        print('./%s/%s/%d.jpg' %(title,chapter,n))
        '''2.this shows TypeError'''
        with open('./%s/%s/%d.jpg','wb' %(title,chapter,n)) as f:
            f.write(requests.get(i).content)
        '''3.this shows TypeError'''
        with open('./%s/%s/'+str(n)+'.jpg','wb' %(title,chapter)) as f:
            f.write(requests.get(i).content)
         '''4.this is correct'''
        with open(dir+str(n)+'.jpg','wb') as f:
           f.write(requests.get(i).content)
在打开的“/%s/%s/%d.jpg”中的“wb”%title,chapter,n中,格式运算符%紧跟在“wb”之后,因此尝试对该字符串而不是文件名模板进行操作

将行更改为打开“./%s/%s/%d.jpg”%title,chapter,n,'wb',它将按预期工作