Please help me with this problem about csv files. I have 2 lists, and I want to write them to a csv file, like this:
X = [12,423,56]
Y = [35,78,321]
The csv file also contains one index column "No" which is auto-generated:
No,X,Y
1,12,35
2,423,78
3,56,321
You can do this with the csv module from the standard library, and the zip and enumerate builtin functions.
with open('myfile.csv', 'w', newline='') as f:
writer = csv.writer(f)
# Write column headers
writer.writerow(['No', 'X', 'Y'])
for i, (a, b) in enumerate(zip(X,Y), start=1):
writer.writerow([i, a, b])
Output:
No,X,Y
1,12,35
2,423,78
3,56,321
The csv
module provides tools for reading and writing csv files.
enumerate
outputs the index of each iteration of a loop; here we configure it to use 1 as it's starting value - by default it starts at zero.
zip
accepts one or more iterables as input, loops over each iterable in-step and yields the elements from succeeding positions in the iterables each time:
etc.
If the iterables are not all of the same length. zip
stops yielding once the shortest iterable has been consumed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.