Comparison of python string inside if

Asked

Viewed 1,113 times

0

My comparison of relatively simple strings doesn’t work and I can’t find the reason.

# -*- coding: UTF-8 -*-

import csv
import os

def sortKeywords():
    keyw = []
    sheetsList = os.listdir('.')
    for sheet in sheetsList:
        if ((os.path.isfile(sheet))and(sheet.endswith(".csv"))):
            file = open(sheet)
            lines = csv.reader(file)
            for line in lines:
                if(line[1] != "Keyword")
                    print(line[1])

sortKeywords()

The following error appears:

inserir a descrição da imagem aqui

  • The problem is you didn’t put the two dots ( : ) to start the conditional code block.

2 answers

1

In Pythos, the "if statements" and cycles always end with :

So just change it:

if(line[1] != "Keyword")

for

if line[1] != "Keyword":
  • I thought I was answering in general, it was a mistake!

1

As some have already commented what should be modified is the two points at the end of the statement of line 14, as pointed out in the image:

if line[1] != "Keyword":

In addition to simply making the change, it is important to understand the error message that has been returned

Every time one is returned SyntaxError means that there was some problem at the time the Python interpreter understood what was written. Just as in a language, as in Portuguese, we have our own syntax rules that refer to the way the language is written. With Python and any other programming language this is no different.

At the moment you run the Python file, an understanding of what has been written is realized (step we call parser). If such a structure is not recognised (comparing to the rules of the language already predetermined), a syntax error is popped, hence the SyntaxError. Even it facilitates pointing the line that occurred.

Syntax Error Reference: https://docs.python.org/3/library/exceptions.html#Syntaxerror

It is always good to try to identify these types of errors that are returned. Making a search for the type of error in the documentation is easier to understand the scenario :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.