Pergunta

I'm having an issue with my script. The error I'm getting below is

File "./filter.py", line 12
with open('test.txt') as f:
        ^
SyntaxError: invalid syntax

The code that I'm using below is this.

with open('test.txt') as f:
    for row in f:                                
        cur.execute("DELETE FROM filterstagetbl where filtersetidn IN (select filtersetidn from filtersettbl where name = '"+row.strip()+"'")
        cur.execute("DELETE FROM filtersetaccesstbl where filtersetidn IN (select filtersetidn from filtersettbl where name = '"+row.strip()+"'")
        cur.execute("DELETE FROM filtersetmembertbl where filtersetidn IN (select filtersetidn from filtersettbl where name = '"+row.strip()+"'")
        cur.execute("UPDATE filtersettbl set status = 4 where name = '"+row.strip()+"'")
    conn.commit()

The script basically connects to DB, looks for a file and delete based on the input of the file.

Foi útil?

Solução

The with statement was added in Python 2.5; you must be using a version older than that.

Either upgrade Python, or not use the with statement; you could use try/finally here to ensure the file object is closed:

f = open('test.txt')
try:
    for row in f:
        # ...
finally:
    f.close()

You should really use SQL parameters to interpolate the row data instead of using string manipulation:

for row in f:
    params = (row.strip(),)
    cur.execute("DELETE FROM filterstagetbl where filtersetidn IN (select filtersetidn from filtersettbl where name = ?",
                params)
    cur.execute("DELETE FROM filtersetaccesstbl where filtersetidn IN (select filtersetidn from filtersettbl where name = ?",
                params)
    cur.execute("DELETE FROM filtersetmembertbl where filtersetidn IN (select filtersetidn from filtersettbl where name = ?",
                params)
    cur.execute("UPDATE filtersettbl set status = 4 where name = ?",
                params)

where you'll need to adjust the parameter placeholder syntax for your database adapter. sqlite3 uses ?, MySQLdb uses %s, as does psycopg2.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top