首页 > 解决方案 > 如何使用 try 块来捕获文件中没有足够的元素

问题描述

我有这个代码:

lis_ = []
with open(_file) as mylines:
    # try: this is for making sure that there enough elements in the file 
    for line in mylines:
        for element in line.split():
            try:
                s_lines = element.split('/')
                s_lines = [int(num) for num in s_lines]
                lis_.append(s_lines)
            except ValueError:
                print('Cannot add to the list: %s' %(s_lines))
    #except: im not quite sure what type of exception it would under        

这从文件中获取值,并且该文件的值必须都是整数,并且格式如下:

'number'-'number' 输出为 [number(int), number]

我的问题是如何确保该文件中的每个元素都是整数,以及如何确保文件中有足够的日期来制作 10 个列表(所以 10 [number,number] 类型的列表)我认为我解决了确保它们都是数字的部分,但我不太确定如何处理数据限制。

编辑:前

文件的内容是:(这些是需要转换为 int 的字符串)

1-2
3-p
5-6
7-8
9-10

这将导致 2 个错误:1 个 ValueError 因为 p 不是数字,另一个错误(这是我努力捕捉的)是文件中没有足够的数据来制作 10 个列表,如下所示:

[1,2][3,4],[5,6],[7,8],[9,10],(如果有足够的数据), [i,i] [i,i] [i, i] [i,i] [i,i] (所以当有足够的数据时,总共有 10 个单独的列表)

标签: python

解决方案


在这种情况下,您可以像这样使用断言块

lis_ = []
with open('file') as mylines:
    try:
        assert len(list(mylines))>=10
        for line in mylines:
            for element in line.split():
                try:
                    s_lines = element.split('-')
                    s_lines = [int(num) for num in s_lines]
                    lis_.append(s_lines)
                except ValueError:
                    print('Cannot add to the list: %s' %(s_lines))
    except AssertionError:
        print('Not enough data')

如果您想了解更多信息,请使用python assert 关键字


推荐阅读