-
StackOverflow 文件
-
Python Language 教程
-
從字串或列表寫入 CSV
-
基本寫例
import csv
#------ We will write to CSV in this function ------------
def csv_writer(data, path):
#Open CSV file whose path we passed.
with open(path, "wb") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for line in data:
writer.writerow(line)
#---- Define our list here, and call function ------------
if __name__ == "__main__":
"""
data = our list that we want to write.
Split it so we get a list of lists.
"""
data = ["first_name,last_name,age".split(","),
"John,Doe,22".split(","),
"Jane,Doe,31".split(","),
"Jack,Reacher,27".split(",")
]
# Path to CSV file we want to write to.
path = "output.csv"
csv_writer(data, path)