所以基本上我的代码是:
def process_contacts(contacts_file):
f = None
sections = []
ret_dic = {}
try:
f = open(contacts_file, 'r')
content = f.readlines()
for line in content:
if "#" in line:
continue
line = line.rstrip("\n")
sections = line.split(',') # section = categories of information on origin file
if sections[1] == '' or len(sections) != 4:
raise ValueError('Invalid input file')
if sections[3] in ret_dic:
if sections[1] not in ret_dic[sections[3]]:
ret_dic[sections[3]].append(sections[1])
else:
ret_dic[sections[3]] = [sections[1]]
except IOError:
print 'Cannot process due to an IO error'
except ValueError:
raise ValueError('Invalid input file')
finally:
if f != None:
f.close()
if sections != []:
return ret_dic
我在加注ValueError
时遇到问题。我需要将ValueError
引发为错误,但是我的代码只是跳过了它,我不明白为什么,我在整个Internet上搜索了它,但是也许我不明白。
无论如何,我打开的csv文件是:
Avi,Levi,Kushnir 7,Jerusalem
Moshe,,Hamakabim 4,Tel Aviv
Michael,Cohen,Herzel 70
Eli,Cohen,Haroe 6,Jerusalem
Moti,Cohen,shalom 5,Tel Aviv
答案 0 :(得分:0)
这是因为您的finally
封锁。您在raise
中ValueError
except
,然后说“哦,没关系”,然后结束finally
。如果遇到错误,finally
块将总是运行。