Table of Contents
CSV writing
The first writing method (by creating a writer object)
The second writing method (use DictWriter to write data using a dictionary)
Reading through reader()
Read through dictreader()
Home Backend Development Python Tutorial Python knowledge summary: writing and reading of csv files

Python knowledge summary: writing and reading of csv files

Apr 02, 2022 pm 12:53 PM
python

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

See all articles