我编写了一个函数来从 csv 文件中获取行数据,但失败了。所以我插入了这么多“打印”来看看出了什么问题。但令我惊讶的是,控制台一直是空的,这很奇怪。我重新缩进了我的代码这么多次我的代码被炸毁了:
# -*- coding: utf-8 -*-
import csv
def get_rows(csv_file):
print '0'
reader=csv.reader(open(csv_file))
print '1'
#get the colnum names,lowercased
col_names=tuple(k.lower() for k in reader.next())
print '2'
for row in reader:
yield dict(zip(col_names,row))
print col_names
def main():
file_name='companylist.csv'
try:
get_rows(file_name)
except:
print 'OK'
if __name__=='__main__':
main()
而代码:
# -*- coding: utf-8 -*-
import csv
reader=csv.reader(open('companylist.csv'))
col_names=tuple(k.lower() for k in reader.next())
for row in reader:
dict(zip(col_names,row))
print col_names
完美地工作,导致:
('symbol', 'name', 'lastsale', 'marketcap', 'adr tso', 'ipoyear', 'sector', 'industry', 'summary quote', '')
而代码:
# -*- coding: utf-8 -*-
import csv
def main():
reader=csv.reader(open('companylist.csv'))
col_names=tuple(k.lower() for k in reader.next())
print '1'
print col_names
for row in reader:
yield dict(zip(col_names,row))
print col_names
if __name__=='__main__':
main()
结果一无所获
和代码:
# -*- coding: utf-8 -*-
import csv
def get_rows(csv_file):
print '0'
reader=csv.reader(open(csv_file))
print '1'
#get the colnum names,lowercased
col_names=tuple(k.lower() for k in reader.next())
print '2'
for row in reader:
yield dict(zip(col_names,row))
print col_names
def main():
file_name='companylist.csv'
try:
if(get_rows(file_name)):
print "OK"
except Exception,ex:
print Exception,":",ex
if __name__=='__main__':
main()
导致:OK