How to save file contents in python?

I just started working on python and this is a very simple question:

I have input.txt that contains the following test cases:

 b---d -d--d --dd- --d-- ----d 

Now I want to save the above content in a 5 X 5 Matrix using python code. So when I want to return matrix[0][2] It returns - .

How can I do it? I tried, but it prints the wrong answer.

+4
source share
2 answers

It is very simple, since lines and files are also iterable:

 with open('input.txt') as matrixfile: matrix = [list(line.strip()) for line in matrixfile] 

list() on a line turns it into a list of individual characters; we use .strip() to remove extra spaces, including a new line. The open matrixfile object is matrixfile , so we can iterate over it to process all the rows.

Result:

 >>> matrix [['b', '-', '-', '-', 'd'], ['-', 'd', '-', '-', 'd'], ['-', '-', 'd', 'd', '-'], ['-', '-', 'd', '-', '-'], ['-', '-', '-', '-', 'd']] >>> matrix[0][2] '-' 
+5
source

So, since Martin was quicker to post the obvious answer, here's another idea:

You donโ€™t need to create a nested list (โ€œmatrixโ€) at all:

 with open("input.txt") as infile: matrix = [line.rstrip() for line in infile] 

gives you a list of five lines that can be indexed (and will return a single character when it is done), just as a nested list can:

 >>> matrix ['b---d', '-d--d', '--dd-', '--d--', '----d'] >>> matrix[0][2] '-' 
+2
source

All Articles