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)