Python Syntax Problem: Complexity of Comment Syntax and Backslash

By Xah Lee. Date:

this is a example of Python syntax voodoo.

why do i get a syntax error in the following?

# traverse the dir, remove temp files
for dpath, dirList, fileList in os.walk(inPath, topdown=False):
    for ff in fileList:
        if (ff == ".htaccess") or \
                (ff == ".DS_Store") or \
      "^xx", ff) or \
      "^#.+#$", ff) or \
                #"~$", ff) or \
      "^xx", ff):
            print("◆", ff)
File "/home/xah/git/xahscripts/make_download_copy/delete_temp_files.py3", line 46
    #"~$", ff) or \
SyntaxError: invalid syntax

if you remove the comment, then it's fine.

here's the tech answer, given by Wang Bin.

A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.


Wang also gave this tip:

BTW, I think a more pythonic way to check is:

for pattern in (r'^\.htaccess$', r'^\.DS_Store$', r'~$', r'^xx'):
    if, ff):
        print ff

original discussion