Python knowledge summary: writing and reading of csv files
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.
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)
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:
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)
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)
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
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)
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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.

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.

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 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.

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 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 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.
