Reputation: 679
I'm writing a huge code and one of the little things I need it to do is go over a text file that is divided to different lines. i need it to create a new list of lines every time the line is empty. for example if the text is: (each number is a new line)
1 2 3 4
5 6 3
1 2
it should build 3 different lists: [1,2,3,4], [5,6,3], [1,2]
this is my code so far (just getting started):
new_list=[] my_list=[] doc=open(filename, "r") for line in doc: line=line.rstrip() if line !="": new_list.append(line) return new_list
Upvotes: 1
Views: 101
Reputation: 309929
You could do something like:
[x.split() for x in fileobject if x.strip()]
To get integers, you could use map
:
[map(int,x.split()) for x in fileobject if x.strip()]
where fileobject
is the object returned by open
. This is probably best to do in a context manager:
with open(filename) as fileobject:
data_list = [map(int,x.split()) for x in fileobject if x.strip()]
Reading some of the comments on the other post, it seems that I also didn't understand your question properly. Here's my stab at correcting it:
with open(filename) as fileobject:
current = []
result = [current]
for line in fileobject:
if line.strip(): #Non-blank line -- Extend current working list.
current.extend(map(int,line.split()))
else: #blank line -- Start new list to work with
current = []
result.append(current)
Now your resulting list should be contained in result
.
Upvotes: 2
Reputation: 5122
Ok, This should work now:
initial_list, temp_list = [], []
for line in open(filename):
if line.strip() == '':
initial_list.append(temp_list)
temp_list = []
else: temp_list.append(line.strip())
if len(temp_list) > 0: initial_list.append(temp_list)
final_list = [item for item in initial_list if len(item) > 0]
print final_list
Upvotes: 3