坚持尝试…除了…其他逻辑

2024-07-05 14:58:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图循环浏览文件夹中的文件,并检查字符串长度(文件名)是否为>;70或<;70个字符,我想看看字符串是否包含“(1”或“(2)”

Schedule RCL 09302009(1 of 2).txt
Schedule RCL 09302009(2 of 2).txt
Schedule RCL 09302010(1 of 2).txt
Schedule RCL 09302010(2 of 2).txt

下面是我正在测试的代码

path = 'C:\\Users\\ryans\\Downloads\\'
all_files = glob.glob(os.path.join(path, "*.txt"))

before = [
        'FFIEC CDR Call Schedule RC',
        'FFIEC CDR Call Schedule RCL'
        ]

after = [
        'FFIEC CDR Call Schedule RC0',
        'FFIEC CDR Call Schedule RCL'
        ]
 
for f in all_files: 
    for b, a in zip(before, after):
        if b in f:
            try:
                if len(f) < 70:
                    string = f[-13:]
                    os.rename(f, path + a + string)
            except:
                if len(f) > 70 & str('(1') in string:
                    string = f[-21:]
                    os.rename(f, path + a + '1' + string)
            else:
                if len(f) > 70 & str('(2') in string:
                    string = f[-21:]
                    os.rename(f, path + a + '2' + string)
            print('can not find file: ' + f)

当我运行代码时,我得到了这个错误

Traceback (most recent call last):

  File "<ipython-input-15-5614012e41f2>", line 105, in <module>
    if len(f) > 70 & str('(2') in string:

TypeError: unsupported operand type(s) for &: 'int' and 'str'

我认为这与此有关:str('(1')

我用str()函数尝试了它,但没有;我得到了相同的错误。我在这里遗漏了什么


Tags: ofpathintxtforstringlenif