我试图循环浏览文件夹中的文件,并检查字符串长度(文件名)是否为>;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()
函数尝试了它,但没有;我得到了相同的错误。我在这里遗漏了什么
关键问题是
&
在Python中是位运算符。您需要执行布尔and,在Python中是and
该行应为:
if len(f) > 70 and str('(2') in string:
布尔运算符: https://docs.python.org/3/reference/expressions.html#boolean-operations
位运算符: https://docs.python.org/3/reference/expressions.html#unary-arithmetic-and-bitwise-operations
相关问题 更多 >
编程相关推荐