CSV files, which are commonly used for data exports, can easily be read or created using the python standard library.
The following program reads the contents of a csv file containing strings separated by commas on multiple lines.
import csv
with open('eggs.csv') as csvfile:
spamreader = csv.reader(csvfile)
for row in spamreader:
print(', '.join(row))
Output:
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam
The following program creates a csv file from strings in a two-dimensional list.
import csv
output_list = [
['Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Baked Beans'],
['Spam', 'Lovely Spam', 'Wonderful Spam']
]
with open('eggs.csv', 'w') as csvfile:
spamwriter = csv.writer(csvfile)
for row in output_list:
spamwriter.writerow(row)
When you run the program, a csv file will be created, containing the values from output_list
. Each sublist corresponds to one line.