This article brings you relevant knowledge about python, which mainly introduces the issues related to writing and reading csv files. CSV is a commonly used text format, used to Store table data, including numbers or characters, I hope it will be helpful to everyone.
Recommended learning: python tutorial
CSV (Comma Separated Values), that is, comma separated values (also known as character separated values, Because the delimiter can be other than a comma), it is a commonly used text format used to store tabular data, including numbers or characters. Many programs will encounter files in the csv format when processing data. Python comes with a csv module, which is specially used to process the reading of csv files.
By creating a writer object, two main methods are used. One is writerow, which writes a line. The other is writerows to write multiple lines
Use DictWriter to write data into it using a dictionary
Let’s talk about the first writing method: writing by creating a writer object (writing one line at a time)
Steps : 1. Create data and table headers 2. Create a writer object 3. Write header 4. Traverse the list and write each row of data into csv
The code is as follows:
import csv person = [('xxx', 18, 193), ('yyy', 18, 182), ('zzz', 19, 185)]# 表头header = ['name', 'age', 'height']with open('person.csv', 'w', encoding='utf-8') as file_obj: # 1:创建writer对象 writer = csv.writer(file_obj) # 2:写表头 writer.writerow(header) # 3:遍历列表,将每一行的数据写入csv for p in person: writer.writerow(p)
After writing, a person.csv file will appear in the current directory. Right-click show in Explorer Open person.csv to view
After opening, you will find that the written data will have line breaks in the middle
Surprisingly : So how should we solve this problem?
hacker: It’s very simple.
Just add a parameter when writing data newline='' In order to prevent line breaks Write
The corrected code is as follows:
import csv# 数据person = [('xxx', 18, 193), ('yyy', 18, 182), ('zzz', 19, 185)]# 表头header = ['name', 'age', 'height']with open('person.csv', 'w', encoding='utf-8', newline='') as file_obj: # 创建对象 writer = csv.writer(file_obj) # 写表头 writer.writerow(header) # 遍历,将每一行的数据写入csv for p in person: writer.writerow(p)
✅By creating a writer object (write multiple lines at once)
Steps : 1. Create data and header 2. Create writer object 3. Write header 4. Pass in the data you want to process in writerows
import csv# 数据person = [('xxx', 18, 193), ('yyy', 18, 182), ('zzz', 19, 185)]# 表头header = ['name', 'age', 'height']with open('person.csv', 'w', encoding='utf-8', newline='') as file_obj: # 创建对象 writer = csv.writer(file_obj) # 写表头 writer.writerow(header) # 3.写入数据(一次性写入多行) writer.writerows(person)
The writing result is as follows:
Notes: When writing using a dictionary, pay attention to the data format passed It must be a dictionary
If it is not a dictionary, an error will be reported
AttributeError: 'tuple' object has no attribute 'keys'
Step 1 .Create data and header ( Data must be in dictionary format) 2. Create DictWriter object 3. Write header 4. Write data
import csv# 数据person = [ {'name': 'xxx', 'age': 18, 'height': 193}, {'name': 'yyy', 'age': 18, 'height': 182}, {'name': 'zzz', 'age': 19, 'height': 185},]# 表头header = ['name', 'age', 'height']with open('person.csv', 'w', encoding='utf-8', newline='') as file_obj: # 1.创建DicetWriter对象 dictWriter = csv.DictWriter(file_obj, header) # 2.写表头 dictWriter.writeheader() # 3.写入数据(一次性写入多行) dictWriter.writerows(person)
import csvwith open('person.csv', 'r', encoding='utf-8') as file_obj: # 1.创建reader对象 reader = csv.reader(file_obj) print(reader)
If you print directly, the csv.reader object will be returned. In this case, you need to traverse the list
<_csv.reader object at>
The corrected code is as follows:
import csvwith open('person.csv', 'r', encoding='utf-8') as file_obj: # 1.创建reader对象 reader = csv.reader(file_obj) # 2.遍历进行读取数据 for r in reader: print(r)
The reading result is as follows:
['name', 'age', 'height']['xxx', '18', '193']['yyy', '18', '182']['zzz', '19', '185']
If you want to print a certain value in the list, you can use index printing
print(r[0])
name xxx yyy zzz
import csvwith open('person.csv', 'r', encoding='utf-8') as file_obj: # 1.创建reader对象 dictReader = csv.DictReader(file_obj) # 2.遍历进行读取数据 for r in dictReader: print(r)
The return result is as follows:
OrderedDict([('name', 'xxx'), ('age', '18'), ('height', '193')])OrderedDict([('name', 'yyy'), ('age', '18'), ('height', '182')])OrderedDict([('name', 'zzz'), ('age', '19'), ('height', '185')])
At this time, if we want to get a certain value, we need to specify the key to find the value
print(r['name'])
xxx yyy zzz
The above is the writing and reading of csv files in the basic python tutorial. If you have suggestions for improvement, please leave a message in the comment area Oh~
Recommended learning: python tutorial
The above is the detailed content of Python knowledge summary: writing and reading of csv files. For more information, please follow other related articles on the PHP Chinese website!