How to Use the csv module to operate csv files in Python

Source: Internet
Author: User
This article mainly introduces how to use the csv module in Python to operate csv files. csv files are formatted data, but csv itself is not as popular as XML and JSON... for more information, see the CSV file "Comma Separated Values". It is a formatted file consisting of rows and columns. The separators can be changed as needed.
The following is a csv file:

Title,Release Date,DirectorAnd Now For Something Completely Different,1971,Ian MacNaughtonMonty Python And The Holy Grail,1975,Terry Gilliam and Terry JonesMonty Python's Life Of Brian,1979,Terry JonesMonty Python Live At The Hollywood Bowl,1982,Terry HughesMonty Python's The Meaning Of Life,1983,Terry Jones

Csv can easily migrate data between different applications. You can export data in batches to the csv format and then import it to other applications. In many applications, You need to export reports in csv format, and then use the Excel tool for subsequent editing.

Print the release date and title and process them one by one:

for line in open("samples/sample.csv"):  title, year, director = line.split(",")  print year, title

Use the csv module for processing:

import csvreader = csv.reader(open("samples/sample.csv"))for title, year, director in reader:  print year, title

Change Separator

Create a csv. excel subclass and change the separator ";"

# File: csv-example-2.pyimport csvclass SKV(csv.excel):  # like excel, but uses semicolons  delimiter = ";" csv.register_dialect("SKV", SKV)reader = csv.reader(open("samples/sample.skv"), "SKV")for title, year, director in reader:  print year, title

If you only need to change one or two parameters, you can directly set them in the reader parameter as follows:

# File: csv-example-3.py import csv reader = csv.reader(open("samples/sample.skv"), delimiter=";") for title, year, director in reader:  print year, title

Save data in CSV format

Generate a csv file using csv. writer.

# File: csv-example-4.py import csvimport sys data = [  ("And Now For Something Completely Different", 1971, "Ian MacNaughton"),  ("Monty Python And The Holy Grail", 1975, "Terry Gilliam, Terry Jones"),  ("Monty Python's Life Of Brian", 1979, "Terry Jones"),  ("Monty Python Live At The Hollywood Bowl", 1982, "Terry Hughes"),  ("Monty Python's The Meaning Of Life", 1983, "Terry Jones")] writer = csv.writer(sys.stdout) for item in data:  writer.writerow(item)

Instance

The following is a complete example. The code is described in the annotations:

Import csv # dialect is one of the parameters that need to be specified when accessing the csv file. It is used to determine the data format of the csv file. # The following function lists which dialect supported by the system. The default value is 'excel ', you can also # derive a class from Dialect and use the instance of this class as the dialect parameter. Print csv. list_dialects () def test_writer (): # The csv file must be open in binary mode with open('eggs.csv ', 'wb') as csvfile: spamwriter = csv. writer (csvfile) spamwriter. writerow (['spam'] * 5 + ['baked Beans ']) spamwriter. writerow (['spam', 'lovely spam', 'Wonderful spam']) def test_reader (): with open('eggs.csv ', 'rb') as csvfile: spamreader = csv. reader (csvfile) for row in spamreader: print row # sniffer is used to infer the format of the csv file, not very accurate def test_sniffer (): with open('eggs.csv ', 'wb') as csvfile: spamwriter = csv. writer (csvfile, delimiter = '') spamwriter. writerow (['spam'] * 2 + ['baked Beans ']) spamwriter. writerow (['spam', 'lovely spam', 'Wonderful spam']) # generally, you must specify the same file format as the writer to correctly read data. with open('eggs.csv ', 'rb') as csvfile: spamreader = csv. reader (csvfile, delimiter = '') for row in spamreader: print ','. join (row) # If you do not know the file format, sniffer can be used with open('eggs.csv ', 'rb') as csvfile: # Use sniffer to infer the file format, dialect = csv. sniffer (). sniff (csvfile. read (1024) print dialect. delimiter, dialect. quotechar # Move the file back to the header csvfile. seek (0) # Use the inferred dialect to create reader = csv. reader (csvfile, dialect) for row in reader: print ','. join (row)

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.