Python csv module usage tutorial

The CSV (Comma Separated Values) format is the most common input and output file format for spreadsheets and databases. The CSV format has been used many years before the RFC 4180 specification was released. Since there was no reasonable standard at that time, there will be subtle differences in the data read and written by different applications. This difference makes it difficult to handle CSV files from multiple sources. But while the delimiters vary, the general format of such files is similar, so it is possible to write a separate module to handle such data efficiently, freeing the programmer from the tedious details of reading and writing the data.

The csv module implements reading and writing of form data in CSV format. It provides functions such as "outputting data files in an Excel-compatible manner" or "reading data files output by an Excel program", and programmers do not need to know the details of the CSV format adopted by Excel. This module can also be used to define CSV formats usable by other applications or to define CSV formats for specific needs.

Recommended tutorial: python official website: csv module Chinese tutorial

The tutorial on the official website is the most comprehensive, but relatively obscure, so please read it patiently!

overview

There are two important APIs in csv:

  • read
    • Function interface:

      with open('eggs.csv', newline='') as csvfile:
          spamreader = csv.reader(csvfile)
          for row in spamreader:
              print(row)
      
    • dictionary interfaceinsert image description here

      with open("./test.csv", "r") as csvfile:
          reader = csv.DictReader(csvfile)
          for row in reader:
              print(row['nnc'])
              print(row['input'])
              print(row['output'])
      
  • write
    • Function interface:insert image description here

      test_list = [
          "January",
          "February",
          "March",
          "April",
          "May",
          "June",
      ]
      with open("./test2.csv", "w") as f:
          cw = csv.writer(f)
          cw.writerow(test_list)
      
    • dictionary interfaceinsert image description here

      	with open("test.csv", "w") as f:
      	    fieldnames = ['nnc', 'input', 'output']
      	    writer = csv.DictWriter(f, fieldnames=fieldnames)
      	    writer.writeheader()
      	    for j in j_info:
      	        writer.writerow(j)
      	        print(j)
      

write csv file

  • dictionary interface

write csv

If you want to write the following content, you can serialize the object from the json file, then transpose the json object, and write the json object into the csv file.
insert image description here


import csv
import json

with open("./test.json", "r") as f:
    j_info = json.loads(f.read())
with open("test.csv", "w") as f:
    fieldnames = ['nnc', 'input', 'output']
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    for j in j_info:
        writer.writerow(j)
        print(j)


  • test.jsondocument content
[
    {
    
    
        "nnc": "name",
        "input": [
            1,
            2,
            3
        ],
        "output": [
            2,
            3,
            4
        ]
    },
    {
    
    
        "nnc": "name",
        "input": [
            1,
            2,
            3
        ],
        "output": [
            2,
            3,
            4
        ]
    },
    {
    
    
        "nnc": "name",
        "input": [
            1,
            2,
            3
        ],
        "output": [
            2,
            3,
            4
        ]
    },
    {
    
    
        "nnc": "name",
        "input": [
            1,
            2,
            3
        ],
        "output": [
            2,
            3,
            4
        ]
    },
    {
    
    
        "nnc": "name",
        "input": [
            1,
            2,
            3
        ],
        "output": [
            2,
            3,
            4
        ]
    }
]

Guess you like

Origin blog.csdn.net/sexyluna/article/details/128474961