[英]Python : How to write list to csv with N items per row
我正在嘗試將列表保存到 csv。 我的代碼是這樣的:
import csv
list = ['John Doe', '51234512214', 'California', 'Student', 'Jane Doe', '1234123123', 'Canada', 'Student', 'Bill Gates', '4123123123211', 'New York', 'Student']
with open(export_file, 'wb') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(list)
myfile.close()
題
我想從每行列表 4 個項目創建 csv。 我的例外 csv 輸出是這樣的:
如何使用最佳 python 方法實現我預期的 csv 文件?
提前致謝。
您可以先創建一個函數來生成 n 大小的塊:
def chunks(lst, n):
for i in range(0, len(lst), n):
yield lst[i:i + n]
然后將生成器中的每個塊寫入 CSV 文件:
with open("output.csv", mode="w", newline="") as csv_out:
csv_writer = writer(csv_out, quoting=QUOTE_ALL)
for chunk in chunks(lst, 4):
csv_writer.writerow(chunk)
完整代碼:
from csv import writer, QUOTE_ALL
lst = [
"John Doe",
"51234512214",
"California",
"Student",
"Jane Doe",
"1234123123",
"Canada",
"Student",
"Bill Gates",
"4123123123211",
"New York",
"Student",
]
def chunks(lst, n):
for i in range(0, len(lst), n):
yield lst[i:i + n]
with open("output.csv", mode="w", newline="") as csv_out:
csv_writer = writer(csv_out, quoting=QUOTE_ALL)
for chunk in chunks(lst, 4):
csv_writer.writerow(chunk)
輸出.csv:
"John Doe","51234512214","California","Student"
"Jane Doe","1234123123","Canada","Student"
"Bill Gates","4123123123211","New York","Student"
您可以將原始列表拆分為 4 個項目的子列表,並使用writerows
將其寫入一次:
import csv
data = ['John Doe', '51234512214', 'California', 'Student', 'Jane Doe', '1234123123', 'Canada', 'Student', 'Bill Gates', '4123123123211', 'New York', 'Student']
rows = [data[i:i+4] for i in range(0, len(data), 4)]
with open(export_file, 'w', newline='') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerows(rows)
注意一些額外的變化:
list
更改為data
:您不應該使用 Python 內置函數的名稱作為變量名(在這里,您將無法使用list
進一步構建列表)'wb'
所做的那樣。newline=''
參數。 正如csv
模塊文檔的最后所述:如果未指定 newline='',則嵌入在引用字段中的換行符將不會被正確解釋,並且在寫入時使用 \\r\\n linendings 的平台上將添加一個額外的 \\r。 指定 newline='' 應該始終是安全的,因為 csv 模塊執行自己的(通用)換行處理。
這是oneliner
import pandas as pd
import numpy as np
your_list = ['John Doe', '51234512214', 'California', 'Student', 'Jane Doe', '1234123123', 'Canada', 'Student', 'Bill Gates', '4123123123211', 'New York', 'Student']
pd.DataFrame(np.reshape(np.array(your_list), (int(len(your_list)/4), 4))).to_csv('your_list_as.csv', index = False, header = False)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.