开发者

Is there something about the os module I'm not getting?

开发者 https://www.devze.com 2023-03-10 17:35 出处:网络
For the last half hour I\'ve been trying to figure out what is wrong with this code. It should be very straight forward. I\'ve practically copied it out of the documentation at this point. But no matt

For the last half hour I've been trying to figure out what is wrong with this code. It should be very straight forward. I've practically copied it out of the documentation at this point. But no matter what I try I receive a syntax error.

Here's the code:

def addfiles(folder):
    foldercont = [os.path.normcase(f) for f in os.listdir(folder)]
    for x in foldercont:
        if os.path.isfile(x) == True:
            files.append(os.path.realpath(x)
        if os.path.isdir(x) == True:
            addfiles(os.path.realpath(x))

Whenever I run this, i receive the error

 if os.path.isdir(x) == True:
                           ^
 SyntaxError: invalid syntax

However, if I write the equivlent code in the interactive interpreter it runs fine.

Can this method simply not be used in an if loop or something?

Th开发者_开发百科anks for the help. I'm getting really frustrated at this point... heh.


There's a parenthesis missing at this line:

files.append(os.path.realpath(x)
                                ^

Python complains about the True: bit because it's expecting a statement like

(x if condition else y)

As jcomeau_ictx says, you should also leave out the == True when checking for booleans:

if x:
    do_something
if not y:
    do_something_else


you're missing a close parentheses on the previous line.

0

精彩评论

暂无评论...
验证码 换一张
取 消