Example of how to read and write csv files using Python,

Source: Internet
Author: User

Example of how to read and write csv files using Python,

This example describes how to read and write csv files in Python. We will share this with you for your reference. The details are as follows:

Create a csvdata.csv file with the following data:

The Code is as follows:

# Coding: utf-8import csv # Read csv file method 1 csvFile = open ("csvData.csv", "r") reader = csv. reader (csvFile) # The returned data type is iteration data = [] for item in reader: print (item) data. append (item) print (data) csvFile. close () # csv file reading method 2 with open ("csvData.csv", "r") as csvfile: reader2 = csv. reader (csvfile) # reads csv files and returns the iteration type for item2 in reader2: print (item2) csvFile. close () # Write the csv file csvFile2 = open('csvFile2.csv ', 'w', newline = '') from the list. # Set newline. Otherwise, a blank line of writer = csv is generated between the two lines. writer (csvFile2) m = len (data) for I in range (m): writer. writerow (data [I]) csvFile2.close () # Write the csv file dic = {'zhang san': 123, 'Li si': 456, 'wang binapa ': 789} csvFile3 = open('csvFile3.csv ', 'w', newline = '') writer2 = csv. writer (csvFile3) for key in dic: writer2.writerow ([key, dic [key]) csvFile3.close ()

For more Python-related content, refer to this topic: python Excel table skill summary, Python coding skill summary, Python data structure and algorithm tutorial, Python function usage skill summary, and Python string operation skill Summary "," Python entry and advanced classic tutorial "and" Python file and directory operation tips summary"

I hope this article will help you with Python programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.