Python操作csv文件方法

DictReader字典读取csv指定列的内容

想要读取“timer Start 8”的内容,或者获取该行其他列的信息,例如获取该行“RO timer expire”列对应的内容:

with open(csvpath,'rb') as csvfile:
    reader = csv.DictReader(csvfile)
    for this_row in reader:
        if this_row['RO timer start'] != "timer start 8":
            # get content of "RO timer expire" column for this row
            get_content = this_row['RO timer expire]

提取csv中指定列并输出到新的csv中

方法1:用csv

太傻b了,每读取一列数据都要执行一次with open操作打开csv,好像没法只进行一次csv打开操作来读取多个列。但有时执行脚本时候用pandas方法又会出bug,用csv打开是绝对不会出错就是了。

with open(csv1path,'rb') as csvfile:
    reader = csv.DictReader(csvfile)            
    frc_list = [row['column1'] for row in reader]
with open(csvpath,'rb') as csvfile:
    reader = csv.DictReader(csvfile)            
    abstime_list = [row['column2'] for row in reader]
with open(csvpath,'rb') as csvfile:
    reader = csv.DictReader(csvfile)            
    roStart_list = [row['column3'] for row in reader]
# 将全部list集合到all_list之后转置,行变列,列变行。之后用writerow方法遍历每个list逐行输出
all_list = zip(column1, column2, column3)

with open(csvpath.replace(csv2path, "wb") as csvFile:
    writer = csv.writer(csvFile)
    # write title for each column
    writer.writerow(['title1', 'title2', 'title3'])
    for row in all_list:
        writer.writerow(row)      

方法2:用pandas

新生成的csv2列明直接沿用csv1中的列名,两行搞定。

import pandas as pd

df = pd.read_csv(csv1path, usecols = ['column1', 'column2', 'column3'])
df.to_csv(csv2path, sep=',', header=True, index=False)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值