Python reads and writes csv files,

Source: Internet
Author: User

Python reads and writes csv files,

Python comes with a csv module. For more details, refer to the official documentation.

I. Read operations

I don't know why, if the 'B' mode is not used when opening the file, there will be a line break. Therefore, to operate the csv file normally in windows, add the B mode. Delimiter to specify the delimiter between the fields of the reader.

Def readData (): with open('csvFile.csv ', 'rb') as fobj: csvFileReader = csv. reader (fobj, delimiter = '-'); header = next (csvFileReader); print header for row in csvFileReader: print row;

Ii. Write operations

Header = ["name", "gender", "Age"]; datas = [("Li Fei", "male", 15), ("Zhang Shan", "male ", 25)]; with open('csvFile.csv ', 'wb') as fobj: csvFileWriter = csv. writer (fobj, delimiter = '-'); csvFileWriter. writerow (header); csvFileWriter. writerows (datas );

These are simple csv file read and write operations. For more information, see the official documentation.

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.