Preface
I remembered that when I used the pandas library function read_excel to read excel, I remembered that another function was read_csv. I thought about using csv or pandas, but I was actually bypassed tonight. I took advantage of this opportunity to learn about the python built-in csv module.
Portal: official document
Read file
The test.csv file is as follows:
序号,参数
1,3
2,6
3,7
import csv
with open("test.csv",'r') as csvfile:
files = csv.reader(csvfile)
for file in files:
print(file)
result:
['序号', '参数']
['1', '3']
['2', '6']
['3', '7']
Write file
import csv
with open('names.csv', 'w', newline='') as csvfile:
fieldnames = ['first_name', 'last_name']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader() # 书写表头
writer.writerow({
'first_name': 'Baked', 'last_name': 'Beans'})
writer.writerow({
'first_name': 'Lovely', 'last_name': 'Spam'})
names.csv content:
first_name,last_name
Baked,Beans
Lovely,Spam
Writing while reading
So far, I have not seen the operation of reading and writing. As far as the programming language is used to operate the same file, it is not recommended to read and write. Because the uncertainty is too strong, it is recommended to use other files to cover.
postscript
More details about the csv library can be found in the portal . Of course, the lesson is that of 对于某些技术点不熟悉,第一应该是查看官方文档,而不是漫无目的地在网络上寻找适配。
course, the online technology is indeed rich, but the best is true.