I am reading in a file that is formatted as the following:
#*title
#tyear
#cVenue
#index0
#!abstract
#*title
#tyear
#cVenue
#index1
#!abstract
with thousands of blocks. Each block is separated by a blank line and each block is a row in a table. I want insert into my table after each block has been read. Then I want to clear the variables so the next block may be read and inserted. Here is my code so far: import 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
There are no errors when I run this code but my table is empty. Could someone point out where I have gone wrong. Should I possibly use a different way of checking if I have come to the end of a block?