user1972880
user1972880

Reputation:

How to save the file content in python?

I just started to work on python and it's a very basic question:

I have a input.txt which contains following test cases:

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

Now i want to save the above content in 5 X 5 Matrix with the help of python code. So that when i want to return matrix[0][2] It returns -.

How should i do that? I tried it but it prints wrong answer.

Upvotes: 3

Views: 110

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

So since Martijn was faster in posting the obvious answer, here's another idea:

You actually 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 strings which can be indexed (and will return a single character when done so) just like the nested list can:

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

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121874

This is very easy, as strings and files are iterables too:

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

list() on a string turns it into a list of the individual characters; we use .strip() to remove any extra whitespace, including the newline. The matrixfile open file object is an iterable, so we can loop over it to process all the lines.

Result:

>>> matrix
[['b', '-', '-', '-', 'd'], ['-', 'd', '-', '-', 'd'], ['-', '-', 'd', 'd', '-'], ['-', '-', 'd', '-', '-'], ['-', '-', '-', '-', 'd']]
>>> matrix[0][2]
'-'

Upvotes: 5

Related Questions