user2714897
user2714897

Reputation: 3

Opening a file- How to make a .txt file return a list of lists

Ok so I have this txt file that I need to open which looks like this when I use the code below (except with actual newline indents, not the \n syntax and the '' equals a space);

"#####\n #   #\n ### #\n #X  #\n #####"

... and then convert this into a list of lists like this;

[['#', '#', '#', '#', '#'],
['#', ' ', ' ', ' ', '#'],
['#', '#', '#', ' ', '#'],
['#', 'X', ' ', ' ', '#'],
['#', '#', '#', '#', '#']]

Here's my code, I'm able to print the normal txt file into Shell but I can't figure out how to convert it like above with the list of lists.

def file_open (filename):
openfile = open(filename, 'rU') 
str1= openfile.read()           
openfile.close()                
print str1

Can anyone help on how to go about doing this?

Upvotes: 0

Views: 132

Answers (2)

TerryA
TerryA

Reputation: 59974

With the string s...:

>>> s = "#####\n #   #\n ### #\n #X  #\n #####"

You can split it by each new line to get:

>>> print s.split('\n')
['#####', ' #   #', ' ### #', ' #X  #', ' #####']

And further split that:

>>> print [list(i) for i in s.split('\n')]
[['#', '#', '#', '#', '#'], [' ', '#', ' ', ' ', ' ', '#'], [' ', '#', '#', '#', ' ', '#'], [' ', '#', 'X', ' ', ' ', '#'], [' ', '#', '#', '#', '#', '#']]

To get your list.

Upvotes: 2

Louis Hugues
Louis Hugues

Reputation: 596

you can simply use the 'eval' function which evaluates any python code stored into a string:

alist = eval(str1)

Note: However take care to the fact that this is unsafe by nature (as the string may contain malicious python code). But maybe it is not your concern here.

Upvotes: 0

Related Questions