-1

I am trying to loop through files in a folder and check if the string length (file name) is >70 or <70 characters, and I want to see if the string contains a '(1' or '(2'. Here are some sample strings.

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

Here is the code that I am testing.

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)

When I run the code I get this error.

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'

I think it has something to do with this: str('(1')

I tried it with the str() function and without; I get the same error. What am I missing here?

ASH
  • 20,759
  • 19
  • 87
  • 200

1 Answers1

1

The key issue is that & is a bitwise operator in Python. You want to do a boolean and, which in Python is and

The line should read:

if len(f) > 70 and str('(2') in string:

Boolean operators: https://docs.python.org/3/reference/expressions.html#boolean-operations

Bitwise operators: https://docs.python.org/3/reference/expressions.html#unary-arithmetic-and-bitwise-operations

mattbornski
  • 11,895
  • 4
  • 31
  • 25