Python handles CSV file instances in detail

Source: Internet
Author: User
Tags jupyter jupyter notebook

Python handles CSV files

CSV (comma-separated values) is a comma-separated value that can be opened for viewing in Excel. Because it is plain text, any editor can also be opened. Unlike the Excel file, the CSV file:

    • Value has no type, all values are string

    • Styles such as font color cannot be specified

    • Cannot specify a cell's width height, cannot merge cells

    • No More worksheets

    • Cannot embed image chart

Separates two cells in a CSV file , as delimiters. This a,,c means that a c there is a blank cell between the cell and the cell. And so on

Not every comma represents the demarcation between cells. So even if the CSV is a plain text file, it is also insisted on using specialized modules for processing. Python has a CSV module built in. Let's take a look at a simple example.

Reading data from a CSV file

Import csvfilename = ' F:/jupyter notebook/matplotlib_pygal_csv_json/sitka_weather_2014.csv ' with open (filename) as F:    reader = Csv.reader (f) Print (list (reader))

dataCan not print directly, list (data) outermost is a list, the inside of each row of data in a list, a bit like this

[[' Name ', ' age '], [' Bob ', ' + '], [' Tom ', ' 23 '], ...]

So we can access Bob's age in this way reader[1][1] , traversing the for loop as follows

Import csvfilename = ' F:/jupyter notebook/matplotlib_pygal_csv_json/sitka_weather_2014.csv ' with open (filename) as F:    reader = Csv.reader (f) for row in reader:# line number starting with 1 print (Reader.line_num, row)

It is important to note that reader can only be traversed once. Because reader is an iterative object, you can use a next method to get one row at a time.

Import csvfilename = ' F:/jupyter notebook/matplotlib_pygal_csv_json/sitka_weather_2014.csv ' with open (filename) as F: Reader    = Csv.reader (f) # reads a line, and the following reader does not already have the line Head_row = Next (reader) for row in reader:# line number starting with 2 print (Reader.line_ num, Row)

Write data to a CSV file

There is reader to read, and of course writer can write. Write one line at a time, and write more than one line at a time.

Import csv# use numbers and string numbers to Datas = [[' Name ', ' age '], [' Bob ', ' + '], [' Tom ', ' + '         ], ['        Jerry ', ']]with ' open (' Example.csv ', ' W ', newline= ') as f:    writer = Csv.writer (f) for row in datas:        writer.writerow (Row)        # You can also write multiple lines of writer.writerows (datas)

If not specified newline='' , a blank line is written to each write line. The above code generates the following.

name,agebob,14tom,23jerry,18name,agebob,14tom,23jerry,18

Dictreader and Dictwriter objects

Using Dictreader, you can manipulate the data like a dictionary, and use the first row of the table (usually the header) as the key. Use key to access the data for that key in the row.

Import csvfilename = ' F:/jupyter notebook/matplotlib_pygal_csv_json/sitka_weather_2014.csv ' with open (filename) as F:    reader = csv. Dictreader (f) for row in reader:# Max Temperaturef is a data for the first row of the table, as Keymax_temp = row[' Max temperaturef ']print (max_temp)

Using the Dictwriter class, you can write data in the form of a dictionary, and the same key is also the header (the first row of the table).

Import csvheaders = [' name ', ' age ']datas = [{' Name ': ' Bob ', ' age ': +},        {' name ': ' Jerry ', ' age ': ', '},        {' name ': ' Tom ', ' age ':        ]with open (' Example.csv ', ' W ', newline= ') as f:# header is passed here as the first line of data writer = csv. Dictwriter (f, headers)    Writer.writeheader () for row in datas:        writer.writerow (Row)        # You can also write multiple lines of writer.writerows (datas)
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.