Home > OS >  Write list of numbers to CSV file in Python
Write list of numbers to CSV file in Python

Time:02-13

I have a list of 4-digit numbers (1234, 1234, 1234) in Python that I would like to write to a CSV file.

I am using the csv library, this is the code I have:

with open('converted2.csv','w') as new_file:
 write=csv.writer(new_file)
 write.writerows(results)

However, when I import the values into a file, they are spread across rows

How could I prevent this from happening and have the four-digit numbers all under one column only?

Thank you!

CodePudding user response:

use the lambda method provided inside writerows to print rows

import csv

results = [1234, 1234, 1234]
with open('converted2.csv','w') as new_file:
 write=csv.writer(new_file)
 write.writerows(map(lambda x: [x], results))

$ cat converted2.csv 
1234
1234
1234
  • Related