简体   繁体   中英

Python error: 'bool' not iterable

I'm trying to run a code:

import os
from os import listdir

for f in sorted(os.listdir("/path")):
    if f in f.startswith("20"):
        for f in sorted(os.listdir(f)):
            if f.endswith(".txt"):
                pass
            else:
                try:
                   os.system("/path/script.py %s" % f)
                except:
                   pass

I have received this error:

Traceback (most recent call last):

 File "files_correct_phase.py", line 5, in <module>
    if f in f.startswith("20"): 
TypeError: argument of type 'bool' is not iterable
 code here

I ran it inside the python prompt and it worked fine after line 5, but when I run it as

python python_script.py

in the command line, it gives me this error. I would be grateful for any advice and/or help.

(Python version 2.7.6)

if f in f.startswith("20"):

is not valid. startswith returns a bool the in keyword trys to check for containment inside your bool . That only works for iterables (which bool is not). You probably want:

if f.startswith("20"):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM