Search code examples
pythonpython-3.xloopsif-statementcontinue

Invalid syntax of Else: 3.8


I'm a newbie in python scripting and would like to know how to fix the code below. I would like to know how to solve the Invalid Syntax of Else statement, thank you!

import os
import zipfile

f = open("filelist.txt","w+")
path=("pathtofile")
directory=os.fsencode(path)
filenames = []
for file in os.listdir(directory):
    filename = os.fsdecode(file)
    if filename.endswith(".zip"):
        with zipfile.ZipFile(filename, 'r') as zipObj:
            contents = zipObj.namelist()

    listfile = (str(contents))
    remchar = "'[]"
    for char in remchar:
            a = listfile.replace(char,"")
    f.write (a)
    continue
    else:
        pass

    f.close()

Solution

  • Remember that indentation in python is significant. Your else: statement has no matching if statement on the same level. Make sure to indent properly to achieve what you're looking for:

    if filename.endswith(".zip"):
        with zipfile.ZipFile(filename, 'r') as zipObj:
            contents = zipObj.namelist()
    
            listfile = (str(contents))
            remchar = "'[]"
            for char in remchar:
                a = listfile.replace(char,"")
                f.write (a)
            continue
    else:
        pass