Reputation: 245
I need to write a function that read from a file and put every some lines as one cell in a list. I need to copy the lines between 1 to 2 and from 2 to the end and put each of them in different cell in the list, without the lines that contains the number and empty lines. I dont have an idea how make it work.
the file:
; 1
####
# .#
# ###
#*@ #
# $ #
# ###
####
; 2
######
# #
# #@ #
# $* #
# .* #
# #
######
my code:
def loader(filename):
levels=[[]]
f=open(filename, "r")
x=[]
for line in f:
if ";" not in line:
x.append(line)
else:
levels.append(x)
f.close()
return levels
output: cell 1:
####
# .#
# ###
#*@ #
# $ #
# ###
####
cell 2:
######
# #
# #@ #
# $* #
# .* #
# #
######
Upvotes: 0
Views: 985
Reputation: 5122
Final best solution:
If you use re
, you can find anything from
; 1
to
; 2
Here's the code:
import re
levels = [x[2:].strip() for x in re.split(';\s*\d', open(filename).read()) if x != '']
older: (compensates for numbers, and gets rid of blank lines completely)
levels = [x[2:].strip() for x in open(filename).read().split(';') if x != '']
OR
levels = [x[1:].strip() for x in open(filename).read().split('; ') if x.strip() != '']
To print the output:
for level in levels:
print level
Or individually:
print levels[0]
print levels[1]
Upvotes: 3
Reputation: 80336
from itertools import groupby as gb
with open(file,'r') as f:
[list(g) for k,g in gb(f.readlines(),lambda x:';'in x or x=='\n') if not k]
Out:
[[u'####\n',
u'# .#\n',
u'# ###\n',
u'#*@ #\n',
u'# $ #\n',
u'# ###\n',
u'####\n'],
[u'######\n',
u'# #\n',
u'# #@ #\n',
u'# $* #\n',
u'# .* #\n',
u'# #\n',
u'######\n']]
Upvotes: 2
Reputation: 1181
Give this a shot:
def loader(filename):
levels,x = [],[]
for line in open(filename,'r'):
line = line.strip('\n').strip()
# Skip blank lines
if line == '':
continue
# Assuming that lines containing ';' mark a new cell, so save the old cell
if ';' in line:
if x != []:
levels.append(x)
x = []
# If the line doesn't contain ';', it is part of the current cell
else:
x.append(line)
# Save the last cell, if there was one
if x != []:
levels.append(x)
return levels
cells = loader("testfile")
You can build the output for the Nth cell with cell_output = '\n'.join(cell[n-1])
:
print '\n'.join(cells[0])
prints your "output cell 1" from above
Upvotes: 2