Python reads CSV file

Source: Internet
Author: User

Python has a package that reads and writes a CSV file, directly import CSV

New Test.csv

1. Write

Import Csvwith Open ("Test.csv","W", encoding='UTF8') asCsvfile:writer=Csv.writer (CSVFile) writer.writerow (["Index","A_name","B_name"]) writer.writerows ([[0, ' A1 ', ' B1 '],[1, ' A2 ', ' B2 '],[2, ' A3 ', ' B3 '])

Using this notation directly will result in one more empty line behind each line of the file

How to Solve

When writing wirterow with Python3, use W mode when opening the file, then take newline= "

Import Csvwith Open ("Test.csv","W", encoding='UTF8', newline="') asCsvfile:writer=Csv.writer (CSVFile) writer.writerow (["Index","A_name","B_name"]) writer.writerows ([[0, ' A1 ', ' B1 '],[1, ' A2 ', ' B2 '],[2, ' A3 ', ' B3 '])

2. Read

Import Csvwith Open ("test.csv","R" as CSVFile:    Reader=csv.reader (csvfile)    for in  Reader:        Print (line)

Python reads CSV file

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.