j.sinu
j.sinu

Reputation: 11

Recieving input file and storing it as a 2D list in Python?

My program needs to take in a .dat or .txt file that contains a "board" , I need to read in and store the board in a 2D list.

Example text file for board:

+---+-----+
|   |     |
|   |=====|
|   |     |
+---+-----+

My question is , how would I convert this file into a 2D list so I can fill in the gaps with specific symbols.Like auto-fill in MS Paint.

Upvotes: 1

Views: 343

Answers (2)

eestrada
eestrada

Reputation: 1603

Files are iterable objects that yield their lines. So all you need to do is:

strlist = list(fp)

If you need each character in a separate item of a list, then use a list comprehension that stuffs each line into a list (thus, you will have a list of lists of individual characters):

strlist = [list(line) for line in fp]

If you need to strip off the new lines:

strlist = [list(line.rstrip('\n')) for line in fp]

This, of course, assumes you have already opened the file with:

fp = open(filepath, mode='rb')

UPDATE:

Here is a full example:

with open('/path/to/my/board.txt', mode='rb') as fp:
    strlist = [list(line.rstrip('\n')) for line in fp]

# What is in the top left corner of the grid.
print(strlist[0][0])

Upvotes: 0

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24164

If you pass a string to the list function, it takes each character in the string, and makes it a separate element of a list:

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

A list comprehension is a way of creating a list whilst iterating over some sequence to create the list's elements:

>>> [x * 2 for x in range(1, 5)]
[2, 4, 6, 8]

To demonstrate we'll use two useful Python facilities, StringIO and pprint. StringIO allows us to define the contents of a file-like object, so we can test code without actually creating the file. pprint pretty prints, which amongst other things wraps lists nicely so they fit on the screen.

We can split the StringIO contents based on the newline character, '\n':

>>> from StringIO import StringIO
>>> from pprint import pprint

>>> contents = StringIO("""+---+-----+
... |   |     |
... |   |=====|
... |   |     |
... +---+-----+""")

>>> matrix = [list(line.strip()) for line in contents]
>>> pprint(matrix)
[['+', '-', '-', '-', '+', '-', '-', '-', '-', '-', '+'],
 ['|', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|'],
 ['|', ' ', ' ', ' ', '|', '=', '=', '=', '=', '=', '|'],
 ['|', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|'],
 ['+', '-', '-', '-', '+', '-', '-', '-', '-', '-', '+']]

Upvotes: 2

Related Questions