Python knowledge summary: writing and reading of csv files

WBOY
Release: 2022-04-02 12:53:10
forward
2944 people have browsed it

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.

Python knowledge summary: writing and reading of csv files

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.

CSV writing

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

The first writing method (by creating a writer object)

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)
Copy after login

After writing, a person.csv file will appear in the current directory. Right-click show in Explorer Open person.csv to view

Python knowledge summary: writing and reading of csv files
Python knowledge summary: writing and reading of csv files
Python knowledge summary: writing and reading of csv files
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)
Copy after login

Python knowledge summary: writing and reading of csv files
✅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)
Copy after login

The writing result is as follows:

Python knowledge summary: writing and reading of csv files

The second writing method (use DictWriter to write data using a dictionary)

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)
Copy after login

Python knowledge summary: writing and reading of csv files

Reading csv

Reading through reader()

import csvwith open('person.csv', 'r', encoding='utf-8') as file_obj:
    # 1.创建reader对象
    reader = csv.reader(file_obj)
    print(reader)
Copy after login

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)
Copy after login

The reading result is as follows:

['name', 'age', 'height']['xxx', '18', '193']['yyy', '18', '182']['zzz', '19', '185']
Copy after login

If you want to print a certain value in the list, you can use index printing

print(r[0])
Copy after login
name
xxx
yyy
zzz
Copy after login

Read through dictreader()

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)
Copy after login

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')])
Copy after login

At this time, if we want to get a certain value, we need to specify the key to find the value

print(r['name'])
Copy after login
xxx
yyy
zzz
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!