0

I've made a simple program that reads a file of 3 lines of text. I've split the lines and get the out put shown from the t2 variable. How do I get rid of the brackets to make it one list?

fname = 'dogD.txt'
fh = open(fname)
for line in fh:
    t2 = line.strip()
    t2 = t2.split()
    print t2

['Here', 'is', 'a', 'big', 'brown', 'dog']
['It', 'is', 'the', 'brownest', 'dog', 'you', 'have', 'ever', 'seen']
['Always', 'wanting', 'to', 'run', 'around', 'the', 'yard']
0

4 Answers 4

4

It can easily done by using extend() method:

fname = 'dogD.txt'
fh = open(fname)
t2 = []
for line in fh:
    t2.append(line.strip().split())
print t2
Sign up to request clarification or add additional context in comments.

Comments

2

They are all different lists, if you want to make them a single list, you should define a list before the for loop and then extend that list with the list you get from the file.

Example -

fname = 'dogD.txt'
fh = open(fname)
res = []
for line in fh:
    t2 = line.strip().split()
    res.extend(t2)
print res

Or you can also use list concatenation.

fname = 'dogD.txt'
fh = open(fname)
res = []
for line in fh:
    t2 = line.strip().split()
    res += t2
print res

Comments

1

You can add all of splitted lines together :

fname = 'dogD.txt'
t2=[]
with open(fname) as fh:
  for line in fh:
    t2 += line.strip().split()
  print t2

You can also use a function and return a generator that is more efficient in terms of memory use :

fname =  'dogD.txt'
def spliter(fname):
    with open(fname) as fh:
      for line in fh:
        for i in line.strip().split():
          yield i

IF you want to loop over the result you can do :

for i in spliter(fname) :
       #do stuff with i

And if you want to get a list you can use list function to convert the generator to a list:

print list(spliter(fname))

1 Comment

@PeterP You're welcome! if it was helpful you can tell this to community by accepting the answer! ;)
0

The operator module defines a function version of the + operator; lists can be added - which is concatenation.

The approach below opens the file and processes each line by stripping/splitting. Then the individually processed lines are concatenated into one list:

import operator

# determine what to do for each line in the file
def procLine(line):
   return line.strip().split()

with open("dogD.txt") as fd:
   # a file is iterable so map() can be used to
   # call a function on each element - a line in the file
   t2 = reduce(operator.add, map(procLine, fd))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.