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']
PeterP
  • 21
  • 3

4 Answers4

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
rishi kant
  • 1,235
  • 1
  • 9
  • 28
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
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
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))
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • Thanks for your help Kasra much appreciated – PeterP Jul 07 '15 at 12:24
  • @PeterP You're welcome! if it was helpful you can tell this to community by [accepting](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235) the answer! ;) – Mazdak Jul 07 '15 at 12:26
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))
emvee
  • 4,371
  • 23
  • 23