我正在开始一个新的应用程序,并着眼于使用ORM - 特别是SQLAlchemy。 对于初学者我创建了一个python脚本,它从一个文件中读取,然后在我的数据库中创建一个表,该表包含在第一个文件的内容中。我现在想要每天读取一个新文件,它们都是相同的格式,然后相应地更新我的数据库。我的第一个文件的代码如下:
import re
import sqlalchemy
from sqlalchemy import Table, Column, Integer, String, Text, Date, MetaData#, ForeignKey
from sqlalchemy.sql import select
from Tkinter import Tk
from tkFileDialog import askopenfilename
metadata = MetaData()
patient_data = Table('Patient_Data', metadata,
Column('DepartmentCode', Text), # replace to String!
Column('Room', Text),
Column('Bed', String(1)),
Column('Name', Text),
Column('Surname', Text),
Column('MiddleName', Text),
Column('Spec', Text),
Column('PatientNr', String(9), primary_key=True),
Column('DOB', Date),
Column('DOA', Date),
Column('OpnKls', Text)
)
mysql_engine = sqlalchemy.create_engine('mysql://root:xxxxxxxx@localhost/test')
mysql_connection = mysql_engine.connect()
metadata.create_all(mysql_engine)
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
#print(filename)
## Open the file with read only permit
#f = open('131213-XSEPR1-LOCA4202-PR10461', "r")
f = open(filename, "r")
add_to_db = []
## use readlines to read all lines in the file
## The variable "lines" is a list containing all lines
lines = f.readlines()
for l in lines:
if re.match('[\s+$]', l):
continue
tokens = [l[0:4],l[7:9],l[13:14],l[17:29].rstrip(),l[30:42].rstrip(),l[43:55].rstrip(),l[56:59],l[61:70],l[72:82],l[84:94],l[97:99]]
if re.match('[A-Z][0-9][A-Z][A-Z]',tokens[0]) and re.match('([0-9]){2}.([0-9]){2}.([0-9]){3}',tokens[7]):
row_to_add = {
'DepartmentCode': tokens[0],
'Room': tokens[1],
'Bed': tokens[2],
'Name': tokens[3],
'Surname': tokens[4],
'MiddleName': tokens[5],
'Spec': tokens[6],
'PatientNr': tokens[7],
'DOB': tokens[8],
'DOA': tokens[9],
'OpnKls': tokens[10]
}
add_to_db.append(row_to_add)
## close the file after reading the lines.
f.close()
mysql_connection.execute(patient_data.insert(), add_to_db)
我是python的新手,这是我在朋友的帮助下做的。你能不能帮助我如何在第一个文件创建的数据库中读取相同格式的第二个文件?
提前感谢任何人的帮助。