Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

Create a csv file with python and put in nested list to it

I have a nested list like this:

[['Bike No.', 'Purchase Date', 'Batt %', 'Last Maintenance', 'KM since Last', 'Service?'], 
['T101', '10/4/2016', '55', '10/1/2017', '25.08', 'N'], 
['T102', '1/7/2016', '10', '15/5/2017', '30.94', 'N'], 
['T103', '15/11/2016', '94', '13/6/2017', '83.16', 'Y'], 
['T104', '25/4/2017', '58', '10/1/2017', '25.08', 'N'], 
['T105', '24/5/2017', '5', '20/6/2017', '93.8', 'Y']]

I want to be able to create a csv file and put in each list into every line ,how do I do it ? In addition ,I want to be able to overwrite the data with a new one whenever ,the list is updated ,how can I do this? Thanks

As of now ,here is the code I have:

        with open(filepath + 'Bike_List_With_Service.csv','w',newline='') as file:
        a=csv.writer(file,delimiter=',')
        data=data
        a.writerows(data)#write each line of data
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the csv module

import csv

rows = [['Bike No.', 'Purchase Date', 'Batt %', 'Last Maintenance', 'KM since Last', 'Service?'], 
['T101', '10/4/2016', '55', '10/1/2017', '25.08', 'N'], 
['T102', '1/7/2016', '10', '15/5/2017', '30.94', 'N'], 
['T103', '15/11/2016', '94', '13/6/2017', '83.16', 'Y'], 
['T104', '25/4/2017', '58', '10/1/2017', '25.08', 'N'], 
['T105', '24/5/2017', '5', '20/6/2017', '93.8', 'Y']]

with open('output.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerows(rows)

Output:

Bike No.,Purchase Date,Batt %,Last Maintenance,KM since Last,Service?
T101,10/4/2016,55,10/1/2017,25.08,N
T102,1/7/2016,10,15/5/2017,30.94,N
T103,15/11/2016,94,13/6/2017,83.16,Y
T104,25/4/2017,58,10/1/2017,25.08,N
T105,24/5/2017,5,20/6/2017,93.8,Y

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...