Home > Back-end >  How to read the numbers from a text file?
How to read the numbers from a text file?

Time:10-22

I want to read a text file whose first line is sequence of elements separated by space and next line is a number.

with open('input.txt') as f:
    lines = f.readlines()
    arr1=lines[0]
    arr = arr1.rstrip()

Result:

invalid literal for int() with base 10: '1 3 9 8 5'

CodePudding user response:

The issue you're having is because you use rstrip and not split. In Python rstrip will strip out trailing whitespace; this does not include normal spaces in the middle of the string. Instead you can use split to split a string into a list based on a delimiter; the default is a space. After that, you can simply loop over every element and turn it into an int with list comprehension.

with open('input.txt') as f:
    lines = f.readlines()
    split_elements=lines[0].split() #Get a list of elements
    int_list = [int(i) for i in split_elements] #Create new list of ints
    print(int_list)

CodePudding user response:

with open('input.txt') as f:
    lines = f.readlines()
    
    # arr1 now contains the first line
    arr1 = lines[0]
    
    # Return a copy of the string with trailing whitespace removed
    # this step is redundant, see filter() below
    # arr = arr1.rstrip()

    # arr.split(' ') creates a list from the line
    # filter(None, ...) removes empty elements
    # map(int, ...) converts each element to integer
    # list(...) generates a list from <map object>
    print(list(map(int, filter(None, arr.split(' ')))))

For example, print(list(map(int, filter(None, ' 0 1 2 3 4 5 '.split(' '))))) prints [0, 1, 2, 3, 4, 5]

  • Related