The basic tutorial of using the csv module in Python to operate csv files,

Source: Internet
Author: User

The basic tutorial of using the csv module in Python to operate csv files,

CSV is called "Comma Separated Values". It is a formatted file consisting of rows and columns. The delimiter can be changed as needed.
The following is a csv file:

Title,Release Date,Director
And Now For Something Completely Different,1971,Ian MacNaughton
Monty Python And The Holy Grail,1975,Terry Gilliam and 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

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 csv
reader = 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.py
import csv
class 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 csv
import 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, which is used to determine the data format of the csv file
# This function lists the dialects supported by the system. The default value is 'excel'. Users can also
# Derive a class from Dialect and use an instance of the class as the dialect parameter.
print csv.list_dialects ()


def test_writer ():
  # csv file must be opened 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, which is 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'])

  # Usually you need to specify the same file format as the writer to read the data correctly
  with open ('eggs.csv', 'rb') as csvfile:
    spamreader = csv.reader (csvfile, delimiter = '')
    for row in spamreader:
      print ',' .join (row)

  # If you don't know the file format, sniffer can come in handy
  with open ('eggs.csv', 'rb') as csvfile:
    # Use sniffer to infer the file format and get dialect
    dialect = csv.Sniffer (). sniff (csvfile.read (1024))
    print dialect.delimiter, dialect.quotechar

    # File moved back to head
    csvfile.seek (0)

    # Create reader with inferred dialect
    reader = csv.reader (csvfile, dialect)

    for row in reader:
      print ',' .join (row) 


Articles you may be interested in:
  • How to generate a CSV file in the Python Django framework
  • How to Write a CSV file using Python
  • How to convert an html table to a CSV file using python
  • Python uses the cx_Oracle module to export data from oracle to csv files
  • How to export data from Python to CSV files that can be read in Excel
  • How to generate a CSV file using a stream response in the Python Django framework
  • Example of using the Python CSV Module
  • How python processes csv data
  • Example of reading csv files using python (using csv in python)


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.