This time, I will describe how to write a CSV file in Python and read the CSV file.
--Write data line by line to the CSV file using a list
--When writing as an appendix, specify `a``` in the argument
mode``` of ``` open```. --Specify ``
" and `in the argument ``` newline``` of
open``` --There is no problem because ``` utf_8``` is specified for the character code (``
encoding) at the time of creation, but the characters at the time of reading so that even a file with BOM can be read normally Specify `` `" utf_8_sig "
in the code ( `encoding```) (
utf_8_sig``` indicates with UTF-8 BOM) --If the characters are garbled when writing CSV, specify ``
utf_8_sig in the character code (` `encoding
) when writing.
test.py
import csv
fle = r"C:\Users\USER\Desktop\test.csv"
with open(file=fle, mode="w", encoding="utf_8", newline="") as wf:
writer = csv.writer(wf)
writer.writerow(["1", "aaa"])
writer.writerow(["2", "bbb"])
writer.writerow(["3", "ccc"])
with open(file=fle, mode="r", encoding="utf_8_sig") as rf:
lines = csv.reader(rf)
for line in lines:
print(line)
Execution result
PS C:\Users\USER> & python c:/Users/USER/Desktop/test.py
['1', 'aaa']
['2', 'bbb']
['3', 'ccc']
PS C:\Users\USER>
I will not describe it in depth.
Recommended Posts