Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write and read csv File in python

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to write and read csv files in python". The explanation in this article is simple and clear, easy to learn and understand. Please follow the ideas of Xiaobian and study and learn "how to write and read csv files in python" together!

CSV (Comma Separated Values), also known as character separated values, is a common text format for storing tabular data, including numbers or characters. Many programs encounter csv files when processing data. Python comes with csv module, specially used to handle csv file reading

csv write

By creating a writer object, two main methods are used. One is writerow, writing a line. The other one is writerows. Write multiple lines.

DictWriter allows you to write data in dictionary style.

The first method of writing (by creating a writer object)

Let's start with the first method of writing: writing one line at a time by creating a writer object.

Steps: 1. Create the data and header 2. Create the writer object 3. Write the header 4. Traverse the list and write each row of data to csv

The code is as follows:

import csvperson = [('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: Create a writer object writer = csv.writer(file_obj) #2: Write the header writer.writerow(header) # 3: Traverse the list, writing each row to 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 to open person.csv to view it.

When you open it, you will find that the written data will be wrapped in the middle

So how do we solve this problem?

Hacker: It's simple.

Just add a parameter newline='' when writing data to prevent newline writing

The corrected codes are as follows:

import csv#data person = [('xxx', 18, 193), ('yyy', 18, 182), ('zzz', 19, 185)]#table header =<$'name', 'age', 'height']with open('person.csv', 'w', encoding='utf-8', newline='') as file_obj: #Creating objects writer = csv.writer(file_obj) #Write the header writer.writerow(header) #Traverse, write each row of data to csv for p in person: writer.writerow(p)

By creating a writer object (writing multiple lines at once)

Steps: 1. Create the data and header 2. Create the writer object 3. Write the header 4. Pass in the data you want to process in the writers

import csv#data person = [('xxx', 18, 193), ('yyy', 18, 182), ('zzz', 19, 185)]#table header =<$'name', 'age', 'height']with open('person.csv', 'w', encoding='utf-8', newline='') as file_obj: #Creating objects writer = csv.writer(file_obj) #Write the header writer.writerow(header) # 3. Write data (write multiple lines at once) writer.writerows(person)

Write the result as follows:

The second writing method (DictWriter allows you to write data in a dictionary way)

Note: Write in a dictionary Note that the data format passed must be a dictionary

If it's not a dictionary, it's wrong.

AttributeError: 'tuple' object has no attribute 'keys'

Steps 1. Create data and header (data must be in dictionary format)2. Create DictWriter object 3. Write header 4. Write data

import csv#data person = [csv {'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. Create DicetWriter object dictWriter = csv.DictWriter(file_obj, header) # 2. Write the header dictWriter.writeheader() # 3. Write data (write multiple lines at once) dictWriter.writerows(person)

csv read via reader() import csvwith open ('person. csv','r', encoding ='utf-8') as file_obj: # 1. Create a reader object reader = csv.reader(file_obj) print(reader)

If printing directly returns csv.reader objects, you need to traverse the list

The correction codes are as follows:

import csvwith open('person.csv', 'r', encoding='utf-8') as file_obj: # 1. Create a reader object reader = csv.reader(file_obj) # 2. Traverse to read data for r in reader: print(r)

Read the following:

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

If you want to print a value from a list, you can print it using an index.

print(r[0]) namexxxyyzzz reads import csvwith open ('person. csv','r', encoding ='utf-8') as file_obj via dictreader(): # 1. Create a reader object dictReader = csv.DictReader(file_obj) # 2. Traverse to read data 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')])

So if we want to get a value, we need to specify the key to find the value.

print(r ['name '])xxxyyyzzz Thank you for reading, the above is the content of "how to write and read csv files in python", after learning this article, I believe that everyone has a deeper understanding of how to write and read csv files in python, and the specific use needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report