简体   繁体   中英

How to use try block to catch not enough elements in a file

I have this code:

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        

this takes values from a file and the values of that file must all be integers and it is formatted like so:

'number'-'number' and the output would be [number(int), number]

My question is how do I make sure that each of the element in that file is an integer and how can make sure that there are exactly enough date in the file to make 10 list (so 10 [number,number] type of list) I think I solved the part of making sure that they are all numbers but I not quite sure how to handle the data limit.

Edit: ex

the contents of the file would be: (these are strings that needs to be converted to int)

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

This would cause 2 errors: 1 would a ValueError because p is not a number and another error (which is what Im struggling to catch) is the fact that there is not enough data in the file to make 10 list which would like this:

[1,2][3,4],[5,6],[7,8],[9,10],(if there is enough data), [i,i] [i,i] [i,i] [i,i] [i,i] (so in total there are 10 individual list when there is enough data)

In this case you could use an assert block like so

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 keyword if you want to learn more about this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM