有时在对文件进行处理时会出现错误,文件比较小还好,但如果文件比较大,查找起来就比较麻烦,那要怎么获取出错
的行号呢?
这里用到了enumerate,通过enumerate来指定索引:
#!/usr/bin/env python #coding:utf-8 #@Author:Andy #Date: 2017/6/18 def parse_data(file_name): with open(file_name, ‘rt‘) as f: for line_no , line in enumerate(f, 1): fields = line.split() try: count = int(fields[0]) except ValueError as e: print("line {} :parse error: {}".format(line_no, e)) if __name__ == ‘__main__‘: parse_data(‘parse_data.txt‘)
parse_data.txt文件内容如下:
当出错时,先打印行号,再输出错误信息:
这 里的enumerate可以通过第二个参数指定初始值,根据人的使用情况,这里指定为1:,默认情况
下为0
但是要注意,对于元组,在利用enumerate时,并不能自动对其进行解包,而是报错:
data = [ (1, 2), (3, 4), (5, 6), (7, 8) ] for x, (m, n) in enumerate(data): print(x, (m,n)) 0 (1, 2) 1 (3, 4) 2 (5, 6) 3 (7, 8)
解包:报错
for x, y, z in enumerate(data): print(x, y, z) Traceback (most recent call last): File "C:\Program Files\Python35\lib\site-packages\IPython\core\interactiveshell.py", line 2869, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-11-138a8a540361>", line 1, in <module> for x, y, z in enumerate(data): ValueError: not enough values to unpack (expected 3, got 2)
时间: 2024-10-13 05:53:14