1.例子
import csv def writeToCSV(fileName): outputFile = open(fileName,'w',newline='') outputWriter = csv.writer(outputFile) #outputWriter = csv.writer(outputFile,delimiter='\t') outputWriter.writerow(['2020/07/25','15:25:00','xt','1']) outputWriter.writerow(['2020/07/25','15:25:00','xt','2']) outputWriter.writerow(['2020/07/25','15:25:00','xt','3']) outputWriter.writerow(['2020/07/25','15:25:00','xt','4']) outputFile.close()
文本模式打开:
用Excel打开:
注意点:
(1)open时指定newline参数值为空串,否则csv文件记录会变成双倍行距
(2)获取csv.writer时可指定列分隔符和行分隔符,例如指定列分隔符为TAB,行分隔符为双倍行距
outputFile = open(fileName,'w',newline='') #outputWriter = csv.writer(outputFile) outputWriter = csv.writer(outputFile,delimiter='\t',lineterminator='\n\n')
文本模式打开:
Excel打开:
小结:列分隔符用默认的逗号,行分隔符用默认的 \n 更好,便于Excel打开
2. 书上的例子
将一个csv文件的第一行去掉,然后保存到另一个目录下
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import csv,os import logging #logging.basicConfig(filename='xx.txt',level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s') logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s') def removeCSVHeader(baseDir): ''' 将baseDir目录下(一级)的csv文件的文件头去掉保存在另一个目录中,不影响原文件 ''' if not os.path.isdir(baseDir): logging.debug(baseDir+'不是一个目录') return desDir = 'headerRemoved' #保存在当前目录下的desDir子目录下 os.makedirs(desDir,exist_ok=True) allFiles = os.listdir(baseDir) count = 0 for csvFilename in allFiles: if (os.path.isfile(csvFilename) and csvFilename.endswith('.csv')): csvFileRObj = open(csvFilename) csvReader = csv.reader(csvFileRObj) csvFileWObj = open(os.path.join(desDir,csvFilename),'w',newline='') csvWriter = csv.writer(csvFileWObj) for row in csvReader: if csvReader.line_num == 1: continue csvWriter.writerow(row) csvFileRObj.close() csvFileWObj.close() count += 1 logging.debug(csvFilename+'转换完成') else: continue logging.debug('共'+str(count)+'个csv文件转换完成') removeCSVHeader('.')
3. 关于CSV的API