python從SQLAlchemy中匯出匯入CSV檔案
阿新 • • 發佈:2018-12-15
讀寫CSV資料
讀csv檔案
將資料讀取為一個元祖的序列
import csv
with open('stocks.csv') as f:
f_csv = csv.reader(f)
headers = next(f_csv)
for row in f_csv:
# Process row
...
row是一個列表。訪問欄位可以用下標。
匯入到sqlalchemy時:
header = Node.__table__.columns.keys() with open(node_csv[0],encoding='utf-8') as csvfile: reader = csv.reader(csvfile) for item in reader: #通過node_id匯入,修改物件屬性值 if 'node_id' in header: node_id = item[header.index('node_id')] b_query = Node.query.filter_by(node_id=node_id) if b_query.count(): b_node = b_query.one() for index in range(1,len(header)): setattr(b_node, header[index], item[index]) db.session.commit()
寫csv檔案
將SQLAlchemy的資料匯出成csv檔案。
使用UTF-8編碼,header從Node表中生成,將需要匯出的專案從表中查詢得到後,寫入一行資料,資料是物件record的header屬性值。
- 使用示例
outpath = os.path.join(db_folder, "backup_node_%s.csv"%projectid) outfile = open(outpath, "w", encoding="utf-8", newline="") outcsv = csv.writer(outfile) header = Node.__table__.columns.keys() records = Node.query.filter_by(project_id=projectid).all() for record in records: outcsv.writerow([getattr(record, c) for c in header ]) outfile.close()