Reputation: 3
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
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
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