python中csv库的使用

CSV文件,是按照逗号进行分隔的文件

一、写入操作

  • 列表形式

    • 逐行写入

      import csv
      
      header = ['name', 'gender', 'age']
      with open('./test.csv', 'w', encoding='utf-8-sig', newline='') as f:
          writer = csv.writer(f)
          writer.writerow(header)
          writer.writerow(['林青霞', '', 45])
          writer.writerow(['成龙', '', 55])
          writer.writerow(['张曼玉', '', 35])
      
      # 如果不设置newline='',则每添加一行数据,中间会添加一个空行
      # 对于有中文的数据,如果想通过excel打开不显示乱码,可以使用utf-8-sig编码,注意读取的时候编码方式要一致
    • 批量写入

      import csv
      
      header = ['name', 'gender', 'age']
      data = [
          ['林青霞', '', 45],
          ['成龙', '', 55],
          ['张曼玉', '', 35]
      ]
      with open('./test.csv', 'w', encoding='utf-8-sig', newline='') as f:
          writer = csv.writer(f)
          writer.writerow(header)
          writer.writerows(data)
  • 字典形式

    • 逐行写入

      import csv
      
      header = ['name', 'gender', 'age']
      
      with open('./test.csv', 'w', encoding='utf-8-sig', newline='') as f:
          writer = csv.DictWriter(f, fieldnames=header)
          writer.writeheader()
          writer.writerow({'name': '林青霞', 'gender': '', 'age': 45})
          writer.writerow({'name': '成龙', 'gender': '', 'age': 55})
          writer.writerow({'name': '张曼玉', 'gender': '', 'age': 35})
    • 批量写入

      import csv
      
      header = ['name', 'gender', 'age']
      data = [
          {'name': '林青霞', 'gender': '', 'age': 45},
          {'name': '成龙', 'gender': '', 'age': 55},
          {'name': '张曼玉', 'gender': '', 'age': 35}
      ]
      
      with open('./test.csv', 'w', encoding='utf-8-sig', newline='') as f:
          writer = csv.DictWriter(f, fieldnames=header)
          writer.writeheader()
          writer.writerows(data)
    • 追加写入

      import csv
      
      header = ['name', 'gender', 'age']
      
      with open('./test.csv', 'a', encoding='utf-8-sig', newline='') as f:
          writer = csv.DictWriter(f, fieldnames=header)
          writer.writerow({'name': '刘德华', 'gender': '', 'age': 50})
      
      # 将文件mode改为: a
      # 不需要再次写入字段行

二、读取操作

  • 列表形式

    import csv
    
    with open('./test.csv', 'r', encoding='utf-8-sig', newline='') as f:
       reader = csv.reader(f)
       for row in reader:
           print(row)
    • 列表形式读取结果示例

      ['name', 'gender', 'age']
      ['林青霞', '', '45']
      ['成龙', '', '55']
      ['张曼玉', '', '35']
      ['刘德华', '', '50']

      注意:csv文件中的数据均为字符串类型,比如age存入的时候是int类型,取出来的时候是str类型

  • 字典形式

    import csv
    
    with open('./test.csv', 'r', encoding='utf-8-sig', newline='') as f:
       reader = csv.DictReader(f)
       for row in reader:
           print(row)
    • 字典形式结果示例

      {'name': '林青霞', 'gender': '', 'age': '45'}
      {'name': '成龙', 'gender': '', 'age': '55'}
      {'name': '张曼玉', 'gender': '', 'age': '35'}
      {'name': '刘德华', 'gender': '', 'age': '50'}

       

posted @ 2022-12-09 05:09  eliwang  阅读(1197)  评论(0编辑  收藏  举报