0
我在被格式化爲以下文件中讀取:蟒蛇,閱讀文本文件,並插入到表
#*title
#tyear
#cVenue
#index0
#!abstract
#*title
#tyear
#cVenue
#index1
#!abstract
數千塊。每個塊由空行分隔,每個塊是表中的一行。我想在每個塊被讀取後插入到我的表中。然後我想清除這些變量,以便讀取和插入下一個塊。這是我到目前爲止的代碼: 進口MySQLdb的
conn = MySQLdb.connect(host="localhost", user="root", db="Literature")
db1 = conn.cursor()
with open("path\to\my\file.txt", "rb") as f:
for line in f:
if line.startswith("#*"):
title = line[2:]
elif line.startswith("#t"):
year = line[2:]
elif line.startswith("#c"):
Venue = line[2:]
elif line.startswith("#index"):
ID = line[6:]
elif line.startswith("#!"):
abstract = line[2:]
elif line == '\n':
db1.execute('''INSERT INTO my_table(
ID, TITLE, YEAR, Venue, ABSTRACT)
VALUES (%s,%s,%s,%s,%s)'''(ID, title, year, Venue, abstract))
conn.commit()
conn.close()
title = None
year = None
Venue = None
ID = None
abstract = None
else:
continue
當我運行這段代碼有沒有錯誤,但我的表是空的。有人能指出我出錯的地方嗎?我是否應該用不同的方式來檢查我是否已經走到了街區的盡頭?
你可能不希望關閉連接在每次迭代 – Joe
還你確定一個空行是「\ n」。嘗試打印它。可能有一個空格,或者它可能是一個空字符串(我不記得Python是如何做它的) – Joe
這是在Windows,Linux或OSX?我知道Linux使用'\ n'作爲換行符和Windows'\ r \ n'(請參閱[此鏈接](http://stackoverflow.com/questions/426397/do-line-endings-differ-between-windows-和Linux版))。所以,如果你使用Windows,你可能永遠找不到只包含'\ n'的行...... –