csv文件的简单操作

csv存储

import csv

# 储存为csv
head = ['奥运会', '比赛大项', '比赛子项', '国家', '姓名', '排名', '成绩']
fp = open('./1月18.csv', mode='w', encoding='utf-8-sig', newline='')
csv_writer = csv.writer(fp, dialect='excel')
csv_writer.writerow(head)

csv_writer.writerow(['2022北京冬奥会', '滑冰', '消化饼', '中国', 'qfz', '1', '100'])

## 读取数据
import csv
exampleFile = open('example.csv')
exampleReader = csv.reader(exampleFile)
exampleData = list(exampleReader)
print(exampleData)
print(exampleData[0])
print(exampleData[0][0])
print(exampleData[1][1])
exampleFile = open('example.csv')         # Reader对象只能循环遍历一次,再次读取需要再次创建对象
exampleReader = csv.reader(exampleFile)
for row in exampleReader:
    print('Row #' + str(exampleReader.line_num) + ' ' + str(row))   # exampleReader.line_num  当前行的编号

## Writer对象
import csv
outputFile = open('output.csv','w',newline='')
outputWriter = csv.writer(outputFile)
outputWriter.writerow(['spam','eggs','bacon','ham'])
outputWriter.writerow(['hello,world!','eggs','bacon','ham'])
outputWriter.writerow(['1,2,3.13,4'])
outputFile.close()

## delimiter及lineterminator参数,设置单元格分隔符及行分隔符
import csv
csvFile = open('output.csv','w',newline='')
csvWriter = csv.writer(csvFile,delimiter=r'\t',lineterminator='\n\n')     # 制表符分割 及 空行换行
csvWriter.writerow(['spam','eggs','bacon','ham'])
csvWriter.writerow(['hello,world!','eggs','bacon','ham','outputFile'])
csvWriter.writerow([1,2,3.13,4])

## 合并当前目录下所有csv文件,并删除表头
# Removes the header from all CSV files in the current working directory.
import csv,os
os.makedirs('headerRemoved',exist_ok=True)
# Loop through every file in the current working directory.
for csvFilename in os.listdir('.'):
    if not csvFilename.endswith('.csv'):
        continue          # skip non-csv files
    print('Removing header from ' + csvFilename + '...')
    # Read the CSV file in (skipping first row)
    csvRows = []
    csvFileObj = open(csvFilename)
    readerObj = csv.reader(csvFileObj)
    for row in readerObj:
        if readerObj.line_num == 1:
            continue     # skip first row
        csvRows.append(row)
    csvFileObj.close()
    # write to the CSV file.
    csvFileObj = open(os.path.join('headerRemoved',csvFilename),'w',newline='')
    csvWriter = csv.writer(csvFileObj)
    for row in csvRows:
        csvWriter.writerow(row)
    csvFileObj.close()


不要害怕告别,要相信,四季更替,花开花落,都是命中注定。