所以我正在从CSV文件中读取两个单元格以将它们相互比较
import csv
portfolio = csv.reader(open(r"c:\testing.csv", "rb"))
APP_TYPE = []
for app_data in portfolio:
APP_TYPE.append(app_data[1])
portfolio1 = csv.reader(open(r"c:\testing.csv", "rb"))
APP_TYPE1 = []
for app_data1 in portfolio1:
APP_TYPE1.append(app_data1[2])
if APP_TYPE1[1] == 'CLIENT' and APP_TYPE[1] == 'A1':
print "yes"
我已经尝试了几次,因为我觉得这是一种可怕的做法,可以说减肥的更好方法是什么?
答案 0 :(得分:2)
读取一次,将csv.reader()
对象用作iterable,使用next()
function跳过第一行,然后使用{{1}读取第二行再次:
next()
这不再读取文件的前两行,在一个步骤中。 import csv
with open(r"c:\testing.csv", "rb") as infh:
reader = csv.reader(infh)
next(reader, None) # skip first row
row = next(reader)
if row[1] == 'A1' and row[2] == 'CLIENT':
print "yes"
语句使用打开的文件对象作为上下文管理器,这意味着它将在读取操作完成时自动关闭。
您还可以使用itertools.islice()
切出1行:
with
对于单个跳过+单个读取,我通常坚持import csv
from itertools import islice
with open(r"c:\testing.csv", "rb") as infh:
reader = csv.reader(infh)
for row in islice(reader, 1, 2): # skip first, only read second row
if row[1] == 'A1' and row[2] == 'CLIENT':
print "yes"
,但跳过多个行next()
时非常宝贵。
答案 1 :(得分:1)
改进:
使用with
(在块末尾为您关闭文件)
只读一次
只读前两行
import csv
with open(r'c:\testing.csv', 'rb') as f:
reader = csv.reader(f)
next(reader) # skip first line
row = next(reader)
if row[1] == 'A1' and row[2] == 'CLIENT':
print 'yes'
为了便于阅读,我使字符串引用一致。