python中csv文件通过什么表示字符_使用python在CSV文件中搜索字符串并写入结果

1586010002-jmsa.png

#!/usr/bin/python

import csv

import re

string_1 = ('OneTouch AT')

string_2 = ('LinkRunner AT')

string_3 = ('AirCheck')

#searched = ['OneTouch AT', 'LinkRunner AT', 'AirCheck']

print "hello Pythong! "

#def does_match(string):

# stringl = string.lower()

# return any(s in stringl for s in searched)

inFile = open('data.csv', "rb")

reader = csv.reader(inFile)

outFile = open('data2.csv', "wb")

writer = csv.writer(outFile, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL)

for row in reader:

found = False

for col in row:

if col in [string_1, string_2, string_3] and not found:

writer.writerow(row)

found = True

#for row in reader:

# if any(does_match(col) for col in row):

# writer.writerow(row[:2]) # write only 2 first columns

inFile.close()

outFile.close()

I'm trying to figure out how to search a CSV file for 3 items. If those items exist print the row. Ideally I would like only Columns 1 and 3 to print to a new file.

Sample Data File

LinkRunner AT Video,10,20

Wireless Performance Video OneTouch AT,1,2

Wired OneTouch AT,200,300

LinkRunner AT,200,300

AirCheck,200,300

解决方案I'm trying to figure out how to search a CSV file for 3 items. If

those items exist print the row. Ideally I would like only Columns 1

and 3 to print to a new file.

Try this:

import csv

search_for = ['OneTouch AT','LinkRunner AT','AirCheck']

with open('in.csv') as inf, open('out.csv','w') as outf:

reader = csv.reader(inf)

writer = csv.writer(outf, delimiter='\t', quotechar='"', quoting=csv.QUOTE_MINIMAL)

for row in reader:

if row[0] in search_for:

print('Found: {}'.format(row))

writer.writerow(row)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值