Python中通过csv的writerow输出的内容有多余的空行
import csv with open('some.csv', 'r') as f: reader = csv.reader(f) for row in reader: print(row) data = [ ('Finance Mic', 'Finance Name'), ('SS', '上海证券交易所'), ('SZ', '深圳证券交易所'), ('CCFX', '中国金融期货交易所') ] with open('some.csv', 'w', newline='') as f: writer = csv.writer(f) for item in data: writer.writerow(item)
newline
# csv格式 # '1,2,3 4,5,6 ' def market_list_to_csv(data): csv = '' csv = '%s%s,%s ' % (csv, 'finance_mic', 'finance_name') for item in data: csv = '%s%s,%s ' % (csv, item.get('finance_mic'), item.get('finance_name')) return csv market_list_data = { "data": [ { "finance_mic": "SS", "finance_name": "上海证券交易所" }, { "finance_mic": "SZ", "finance_name": "深圳证券交易所" }, { "finance_mic": "CCFX", "finance_name": "中国金融期货交易所" } ] } #print(market_list_to_csv(market_list_data.get('data'))) # ? def real_to_csv(data): csv = '' csv = '%s%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s ' % (csv, 'en_prod_code', 'data_timestamp', 'shares_per_hand', 'open_px', 'high_px', 'low_px', 'last_px', 'business_amount', 'business_balance', 'offer_grp', 'bid_grp') for k,v in data.items(): if not k is 'fields': csv = '%s%s,' % (csv, k) v.pop() v.pop() csv = csv + '%d,%d,%d,%d,%d,%d,%d,%d ' % tuple(v) return csv real_data = { "data": { "snapshot": { "fields": [ "data_timestamp", "shares_per_hand", "open_px", "high_px", "low_px", "last_px", "business_amount", "business_balance", "offer_grp", "bid_grp" ], "600570.SS": [ 150305133, 100, 53980, 56000, 52510, 54950, 14465811, 788995643, "54850,9887,0,54860,1500,0,54900,13300,0,54950,10000,0,54990,800,0,", "54820,8000,0,54810,2100,0,54800,202900,0,54770,100,0,54720,1200,0," ], "000001.SZ": [ 153229327, 100, 15560, 15830, 15300, 15480, 170012067, 2634796408, "15490,93700,0,15500,260609,0,15510,69996,0,15520,87008,0,15530,71400,0,", "15480,438292,0,15470,149000,0,15460,411400,0,15450,414573,0,15440,303733,0," ] } } } print(real_to_csv(real_data.get('data').get('snapshot')))