讀寫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()
引用
- 讀寫CSV資料
- Reading a UTF8 CSV file with Python
- How to write UTF-8 in a CSV file