A supplement to the python CSV module mentioned earlier.
Honestly, you can understand it by document or google, Keep it as a memorandum
If you want to open a CSV file and write it to another file as it is Use the reader method to pass in list format
At this time, the return value of the reader method is of course in list format.
import csv
data=[]
#Read CSV in list format
with open('data.csv' , 'r', newline='' , encoding='utf-8') as f:
r = csv.reader(f)
data = [ i for i in r ]
#Write CSV in list format
with open('data.csv' , 'w', newline='' , encoding='utf-8') as f:
w = csv.writer(f)
w.writerows(data)
At this time, the data is entered in the following multiple list.
[['python', '1'], ['php', '1']]
When writing with writerow, a list is passed as an argument, Note that you have to writerows for multiple lists like the one above.
If you try writerow, the return value will be as follows (returned as a one-line list)
"['python', '1']","['php', '1']"
If you do write rows, the return value will be as follows.
python,2
php,2
Use DictReader method to pass in dictionary format
At this time, the return value of the DictReader method is of course in dictionary format.
from collections import defaultdict
import csv
data = defaultdict(int)
with open('data.csv' , 'r', newline='' , encoding='utf-8') as f:
r = csv.DictReader(f)
data = [ i for i in r ] #Store dictionary in list
with open('data.csv' , 'w', newline='' , encoding='utf-8') as f:
fieldnames =['Name', 'Count']
w = csv.DictWriter(f, fieldnames= fieldnames)
w.writerows(data)
If you look inside the variables as in the case of the list, the data variables will be as follows
[{'Name': 'python', 'Count': '1'}, {'Name': 'php', 'Count': '1'}]
This time the keys and values come in as a dictionary
When writing, the list is passed as an argument to the writerow method, so Actually, it is an image of passing the contents of the dictionary in a list
If you try to write with writerow as in the case of list, Attribute Error will occur as follows I get angry that the list object doesn't have an attribute called key
AttributeError: 'list' object has no attribute 'keys'
If you use writerows, you can write as follows as in the case of list
python,1
php,1
I understand that the writerows method is used when passing both the basic list and the dictionary multiple times.
Recommended Posts