python_csv模块学习

csv模块官方文档https://docs.python.org/3/library/csv.html
读csv文件

import csv

rpath = r'E:\xxx.csv'
with open(rpath) as rf:
    reader = csv.reader(rf)  #使用reader时,row[0]用数字代表某一列
    for row in reader:
        print(row[0],row[1])
import csv

rpath = r'E:\xxx.csv'
with open(rpath) as rf:
    reader = csv.DictReader(rf)#采用DictReader时,可直接使用row['日期']列名读取数据
    for row in reader:
        print(row['日期'],row['股票代码'])

写csv文件:

import csv

wpath = r'E:\xxx_copy.csv'
with open(wpath,'w') as wf:
    writer = csv.writer(wf)
    writer.writerow(['Spam'] * 5 + ['Baked Beans'])
    writer.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
print('success')
import csv

wpath = r'E:\xxx_copy.csv'
with open(wpath, 'w') as wf:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(wf, fieldnames=fieldnames)#使用DictWriter可以定义第一行的列名
    writer.writeheader()#写入第一行的列名
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
print('success')

将一个csv文件中的数据读出并写入到另一个文件中

import csv
rpath=r'E:\xxx.csv'
wpath=r'E:\xxx_copy.csv'

with open(rpath,'r') as rf:
    reader = csv.reader(rf)
    with open(wpath,'w') as wf:
        writer = csv.writer(wf)
        header = next(reader)#读取第一行的字段
        writer.writerow(header)#将第一行的字段写入文件中
        for row in reader:
            if row[0]<'2016-01-01':#写入满足条件的字段
                print('1',row)
                break
            if int(row[11])>2743643:
                print('2',row)
                writer.writerow(row)
print('success')

根据官方文档,csv文件的读写还有很多属性可以使用,需要的时候继续学习

你可能感兴趣的:(python学习)