Work with csv
A tutorial to kick start
Read csv file
Run the following script from this example
import csv
with open('assets/first.csv') as f:
reader = csv.reader(f)
for row in reader:
print(row)
We can see that it prints out the whole csv in first.csv
file in assets
folder
Try editing that file to check!
We can also rewrite it and group it like the following
import csv
def read_csv_rows(file_path):
with open(file_path) as f:
reader = csv.reader(f)
for row in reader:
print(row)
if __name__ == "__main__":
read_csv_rows('assets/first.csv')
import csv
our_new_file = 'assets/_new.csv'
# Create a new csv called _new.csv
with open(our_new_file, 'w') as f:
spamwriter = csv.writer(f)
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
# Read _new.csv just like we what did just now
with open(our_new_file) as f:
reader = csv.reader(f)
for row in reader:
print(row)
Here we go, we get a new csv file named _new.csv
in assets/
folder
Put it all together, we have two functions
import csv
def read_csv_rows(file_path):
with open(file_path) as f:
reader = csv.reader(f)
for row in reader:
print(row)
# here rows as a list of row
def write_csv_rows(file_path, rows):
with open(file_path, 'w') as f:
writer = csv.writer(f)
for row in rows:
writer.writerow(row)
if __name__ == "__main__":
test_file_path = 'assets/_new.csv'
write_csv_rows(test_file_path, [
['Hello', 'this', 'is', 'a', 'new', 'row'],
['Hello', 'this', 'is', 'another', 'new', 'row'],
['It', 'can', 'have', 'different', 'length'],
])
read_csv_rows(test_file_path)