时间:2021-07-01 10:21:17 帮助过:35人阅读
‘‘‘将csv数据导入数据库‘‘‘ import sys import csv import sqlite3 #解析csv文件 def parsecsvFile(filepath): header = None data = [] with open(filepath, ‘r‘) as csvfile: filereader = csv.reader(csvfile) header = next(filereader) #print (header) for row in filereader: data.append(row) #print (data) return header,data #使用sqlite3写数据库 def initdb(header, data): conn = sqlite3.connect("sqlite.db") print ("connect database success") conn.execute("drop table IF EXISTS student") conn.commit() query = ‘‘‘create table IF NOT EXISTS student( Supplier Name VARCHAR(32), Invoice Number VARCHAR(16), Part Number VARCHAR(16), Cost VARCHAR(16), Purchase Date DATE);‘‘‘ conn.execute(query) conn.commit() statement = "INSERT INTO student VALUES(?,?,?,?,?)" conn.executemany(statement, data) conn.commit() curson = conn.execute("select * from student") conn.commit() print (curson) rows = curson.fetchall() print (rows) conn.close() return rows #根据数据库内容写csv文件 def wirtecsvfile(writefilepath, header, data): with open(writefilepath, ‘a+‘) as writefile: writer = csv.writer(writefile, delimiter=",") writer.writerow(header) for row in data: writer.writerow(row) if __name__ == "__main__": readfilepath = sys.argv[1] writefilepath = sys.argv[2] header,data = parsecsvFile(readfilepath) rows = initdb(header, data) wirtecsvfile(writefilepath, header, rows)
Python之sqlite3
标签:[] pat 修改 san 查询 class file ecs 十分