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 format Files in python

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

Share

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

This article mainly shows you the "python csv format file how to write and read", the content is easy to understand, clear, hope to help you solve your doubts, the following let Xiaobian lead you to study and learn "how to write and read csv format file in python" this article.

A brief introduction to csv

CSV (Comma Separated Values), or comma-separated values (also known as character-separated values, because delimiters can not be commas), is a common text format used to store tabular data, including numbers or characters. Many programs encounter files in the format of csv when dealing with data. Python has its own csv module, which is specially used to process the reading of csv files.

Writing of csv

1 two main methods are used by creating a writer object. One is writerow, which is written on one line. The other is that writerows writes multiple lines.

2 using DictWriter, you can write data into it by using a dictionary

The first write method (by creating a writer object)

✅ first talks about the first way to write: write by creating a writer object (one line at a time)

Step: 1. Create data and header 2. Create writer object 3. Write header 4. Iterate through the list, writing each row of data to csv

The code is as follows:

Import csvperson = [('xxx', 18,193), (' yyy', 18,182), ('zzz', 19,185)] # header header = [' name', 'age',' height'] with open ('person.csv',' wicked, encoding='utf-8') as file_obj: # 1: create writer object writer = csv.writer (file_obj) # 2: write header writer.writerow (header) # 3: traverse the list Write the data of 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 view.

When you open it, you will find that there is a line break in the middle of the written data.

Unexpectedly: so how to solve this problem?

Hacker: it's very simple

You only need to add a parameter newline='' when writing data to prevent line breaks.

The corrected code is as follows:

Import csv# data person = [('xxx', 18,193), (' yyy', 18,182), ('zzz', 19,185)] # header header = [' name', 'age',' height'] with open ('person.csv',' wow, encoding='utf-8') Newline='') as file_obj: # create object writer = csv.writer (file_obj) # write header writer.writerow (header) # traversal Write the data of each row to csv for p in person: writer.writerow (p)

✅ by creating a writer object (writing multiple lines at once)

Step: 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# data person = [('xxx', 18,193), (' yyy', 18,182), ('zzz', 19,185)] # header header = [' name', 'age',' height'] with open ('person.csv',' data, encoding='utf-8', newline='') as file_obj: # create object writer = csv.writer (file_obj) # write header writer.writerow (header) # 3. Write data (write multiple lines at once) writer.writerows (person)

The write result is as follows:

The second method of writing (using DictWriter, you can write data using a dictionary)

Note: write using a dictionary to note that the format of the data passed must be a dictionary

If it is not a dictionary, it will report an error.

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# data person = [{'name':' xxx', 'age': 18,' height': 193}, {'name':' yyy', 'age': 18,' height': 182}, {'name':' zzz', 'age': 19,' height': 185},] # header header = ['name',' age', 'height'] with open (' person.csv',' Encoding='utf-8', newline='') as file_obj: # 1. Create the 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 through reader () read import csvwith open ('person.csv',' ritual, encoding='utf-8') as file_obj: # 1. Create a reader object reader = csv.reader (file_obj) print (reader)

If direct printing returns a csv.reader object, you need to traverse the list

The correction code is as follows:

Import csvwith open ('person.csv',' ritual, encoding='utf-8') as file_obj: # 1. Create the reader object reader = csv.reader (file_obj) # 2. Traversing to read data for rin reader: print (r)

The reading result is as follows:

['name',' age', 'height']

['xxx',' 1800, '1932]

['yyy',' 18', '182']

['zzz',' 1900, '185']

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

Print (r [0])

Name

Xxx

Yyy

Zzz

Read import csvwith open ('person.csv',' ritual, encoding='utf-8') as file_obj: # 1 through dictreader (). Create the reader object dictReader = csv.DictReader (file_obj) # 2. Traversing to read data for rin dictReader: print (r)

The returned result is as follows:

OrderedDict ([('name',' xxx'), ('age',' 18'), ('height',' 19')])

OrderedDict ([('name',' yyy'), ('age',' 18'), ('height',' 182')])

OrderedDict ([('name',' zzz'), ('age',' 19'), ('height',' 185')])

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

Print (r ['name'])

Xxx

Yyy

Zzz

The above is all the contents of the article "how to write and read csv files in python". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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