我正在尝试读取csv文件并在条件满足时打印行。
reader = csv.reader(open(csvfile, 'r'))
for row in reader :
print row
try:
(location_id, vrm, valid_datetime) = [x.decode('utf-8-sig') for x in row if row [0] != '297']
except:
print "Error with row: " % row
我只需打印行[0] =='295',但这是打印文件中的所有行。
答案 0 :(得分:0)
我只需打印行[0] =='295',但这是打印文件中的所有行。
当然,是的,这就是你要求的:
for row in reader :
print row
如果您只想打印与给定条件匹配的行,则必须在打印前测试此条件:
for row in reader :
if row[0] != '295':
continue
print row
# etc
请注意列表表达式中的条件:
(location_id, vrm, valid_datetime) = [x.decode('utf-8-sig') for x in row if row [0] != '297']
不会“过滤”具有row [0] != '297'
的行 - 它的作用实际上是:
decoded = []
for x in row:
if row[0] != '297':
decoded.append(x.decode('utf-8-sig'))
(location_id,vrm,valid_datetime)=已解码
IOW:如果row[0] != '297', it creates a list of decoded values, else an empty list, then it tries to unpack the list into
location_id,vrm,valid_datetime . If
row [0] =='297',则列表为空,因此解包将失败并显示ValueError: need more than 0 values to unpack
- 您将拥有发现没有你的荒谬尝试/除了阻止错误信息的块。
IOW,不使用bare except子句,捕获预期的异常(您可以处理的异常),至少打印异常消息:
try:
(location_id, vrm, valid_datetime) = [x.decode('utf-8-sig') for x in row]
except exception as e:
print >> sys.stderr, "Error with row '%s' : %s" % (row, e)
最后一个提示:不要依赖Python关闭文件,这不是语言所保证的。使用with
构造确保您的文件将被关闭,无论发生什么:
with open(csvfile, 'r') as f:
reader = csv.reader(f)
for row in reader :
# your code here