Python CSV module instance and pythoncsv module instance

Source: Internet
Author: User

Python CSV module instance and pythoncsv module instance

The usage of the Python CSV module includes: reader, writer, DictReader, DictWriter. register_dialect.

I have always liked python's csv module, which is easy to use and often used in projects. Here are some examples.
Copy codeThe Code is as follows:
Reader (csvfile [, dialect = 'excel '] [, fmtparam])

Parameter table:

Csvfile
It must be an Iterator-supported object, and the return value of each call to the next method is a string, a common file object, or a list) all objects are applicable. If they are file objects, you need to add the "B" flag parameter to open them.

Dialect
Encoding style. The default format is excel, which is separated by commas (,). In addition, the csv module supports excel-tab style, that is, tab style. You need to define other methods, and then you can call the register_dialect method to register and the list_dialects method to query the list of registered encoding styles.

Fmtparam
The format parameter is used to overwrite the encoding style specified by the dialect object.

Example:
Copy codeThe Code is as follows:
Import csv

Reader = csv.reader(file('your.csv ', 'rb '))
For line in reader:
Print line
 

Writer (csvfile [, dialect = 'excel '] [, fmtparam])

Parameter table (omitted: Same as reader, see above)

Example:
Copy codeThe Code is as follows:
Import csv

Writer = csv.writer(file('your.csv ', 'wb '))
Writer. writerow (['column1 ', 'column2', 'column3 '])
Lines = [range (3) for I in range (5)]
For line in lines:
Writer. writerow (line)

DictReader

Similar to reader, CSV is used for reading, but a dictionary (dict) type is generated instead of an iteration type.

DictWriter

I mainly want to talk about DictWriter. Why do I like DictWriter? Because you need to create a list manually for a common writer, especially when submitting a list through a form, I have been developing on the zope platform, and zope supports an advanced form data model, that is, you can add the corresponding flag when defining the form to automatically generate a records type for the submitted form data, that is, each data item is generated as a dictionary list. In this way, it is very convenient for me to directly pass the form data to DictWriter to generate a csv. Of course, this is the premise that you can ensure the correctness of the data. Next, let's briefly describe the zope advanced form data type.

Example:
Copy codeThe Code is as follows:
<Form action = 'test _ form_action 'method = post>
<Input type = "text" name = "rows. Column1: records" value = "0"/>
<Input type = "text" name = "rows. Column2: records" value = "1"/>
<Input type = "text" name = "rows. Column3: records" value = "2"/>
<Input type = "text" name = "rows. Column4: records" value = "3"/>
<Br/>
<Input type = "text" name = "rows. Column1: records" value = "0"/>
<Input type = "text" name = "rows. Column2: records" value = "1"/>
<Input type = "text" name = "rows. Column3: records" value = "2"/>
<Input type = "text" name = "rows. Column4: records" value = "3"/>
<Br/>
<Input type = "text" name = "rows. Column1: records" value = "0"/>
<Input type = "text" name = "rows. Column2: records" value = "1"/>
<Input type = "text" name = "rows. Column3: records" value = "2"/>
<Input type = "text" name = "rows. Column4: records" value = "3"/>
<Br/>
<Input type = "text" name = "rows. Column1: records" value = "0"/>
<Input type = "text" name = "rows. Column2: records" value = "1"/>
<Input type = "text" name = "rows. Column3: records" value = "2"/>
<Input type = "text" name = "rows. Column4: records" value = "3"/>
<Br/>
<Input type = "text" name = "rows. Column1: records" value = "0"/>
<Input type = "text" name = "rows. Column2: records" value = "1"/>
<Input type = "text" name = "rows. Column3: records" value = "2"/>
<Input type = "text" name = "rows. Column4: records" value = "3"/>
<Br/>
<Input type = "submit" value = "Submit CSV"/>
</Form>

The result after the form is submitted is:
Copy codeThe Code is as follows:
Rows = [{'column1 ': '0', 'column2': '1', 'column3 ': '2', 'column4': '3 '},
{'Column1 ': '0', 'column2': '1', 'column3 ': '2', 'column4': '3 '},
{'Column1 ': '0', 'column2': '1', 'column3 ': '2', 'column4': '3 '},
{'Column1 ': '0', 'column2': '1', 'column3 ': '2', 'column4': '3 '},
{'Column1 ': '0', 'column2': '1', 'column3 ': '2', 'column4': '3'}]

In this way, you can directly call the DictWriter. writerows method for processing:
Copy codeThe Code is as follows:
Import csv

Fieldnames = ['column1 ', 'column2', 'column3 ', 'column4']
Dict_writer = csv.DictWriter(file('your.csv ', 'wb'), fieldnames = fieldnames)
Dict_writer.writerow (fieldnames) # Add the first line of CSV
Dict_writer.writerows (rows) # rows is the data submitted by the form.

* Note: Writing csv files here requires the support of the External Method, because in zope, the csv module cannot be directly operated to read and write the file system due to permission sandbox issues.

 
Is it very convenient to use it in this way? The DTML code for generating the above form is provided here:
Copy codeThe Code is as follows:
<Form action = 'test _ form' method = post>
<Dtml-in "range (5)">
<Dtml-in "range (4)">
<Input type = "text" name = "rows. Column & dtml-sequence-number;: records" value = "& dtml-sequence-item;"/>
</Dtml-in>
<Br/>
</Dtml-in>
<Input type = "submit" value = "Submit CSV"/>
</Form>

You can rewrite the form generation based on your own needs.

References:
Http://docs.python.org/lib/module-csv.html
Http://www.python.org/dev/peps/pep-0305/

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.