fout语法错误

时间:2014-04-29 16:15:31

标签: python syntax-error with-statement

我的脚本出现问题。我遇到的错误是

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

我在下面使用的代码就是这个。

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()

该脚本基本上连接到DB,根据文件的输入查找文件和删除。

1 个答案:

答案 0 :(得分:0)

在Python 2.5中添加了with语句;您必须使用早于此版本的版本。

升级Python,或者不使用with语句;您可以在此处使用try / finally来确保文件对象已关闭:

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

您应该使用SQL参数来插入行数据,而不是使用字符串操作:

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)

您需要调整数据库适配器的参数占位符语法。 sqlite3使用?,MySQLdb使用%spsycopg2也是如此。