Search code examples
pythonlistinputfile-read

How to read input given as integers divided by space and separated to different lines (txt)


I am doing this coding challenge in Python and in the challenge, the input is given as lines of integers separated by space in a file called "input.txt" like so:

3 3 1
1 0 3 1
2 2

Each line represents different part of an input, like the first line is width and height of a grid and number of walls in it, second line are coordinates of start and end and third are coordinates of a specific wall. How would you read the file, so you will at the end get a list, where each line is a separate item in the list, like so:

input = [[3, 3, 1], [1, 0, 3, 1], [2, 2]]
# the numbers are integers

Thanks for answer


Solution

  • with open('input.txt', 'r') as infile:
        # iterating through a file will naturally iterate line-by-line
        # str.split() will split on spaces naturally, and we can convert to int for each value
        # thus, a nested list comprehension
        inp = [[int(i) for i in line.split()] 
               for line in infile]