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.