1

I have a file in the format of one word for line, and I want to join the lines with one space, I tries this, but it does not work

for line in file:
    new = ' '.join(line)
    print (new)

also this does not work

    new = file.replace('\n'', ' ')
    print (new)
fff
  • 111
  • 1
  • 9

5 Answers5

2

You can also use list comprehensions:

whole_string = " ".join([word.strip() for word in file])
print(whole_string)
Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60
  • yes you can, but there is no point in creating a list when you can use a generator. There is a difference. – Pynchia Oct 07 '15 at 20:35
  • @Pynchia, it is actually more efficient to pass a list, if you pass a generator python will construct a list anyway as it does two passes over the data – Padraic Cunningham Oct 07 '15 at 20:37
  • @PadraicCunningham alright thank you. Do you mean Chad Simmons'/Peter Wood's solution are less optimized than this one? Good to know – Pynchia Oct 07 '15 at 20:39
  • @Pynchia, yes, join checks the size first before it actually joins the strings so if it did not first create a list when passed a generator you would not be able to do a second pass over it as the generator would be consumed – Padraic Cunningham Oct 07 '15 at 20:42
  • 1
    OK, upvoted then! :) @PadraicCunningham why is `join` behaving like that? What's the use of checking the size.. of what? – Pynchia Oct 07 '15 at 20:44
  • 1
    @Pynchia, how much space is needed for the output https://github.com/python/cpython/blob/master/Objects/stringlib/join.h#L54 – Padraic Cunningham Oct 07 '15 at 20:52
  • 1
    @PadraicCunningham are you saying `list(word.strip() for word in words)` is slower than `[word.strip() for word in words]`? I'll have to time it. – Peter Wood Oct 07 '15 at 20:57
  • @PeterWood, yes, it is definitely slower. – Padraic Cunningham Oct 07 '15 at 20:59
  • 1
    @PadraicCunningham Well, I never: 2.23 vs 3.12 best of three. About 1.4 times slower. – Peter Wood Oct 07 '15 at 21:02
1

You can add each line to a list, then join it up after:

L = []
for line in file:
    L.append(line.strip('\n'))

print " ".join(L)

Your current solution tries to use join with a string not a list

TerryA
  • 58,805
  • 11
  • 114
  • 143
1

A one line solution to this problem would be the following:

print(open('thefile.txt').read().replace('\n', ' '))

Zack Tanner
  • 2,560
  • 1
  • 29
  • 45
0

This is I think what you want..

' '.join(l.strip() for l in file)
Chad S.
  • 6,252
  • 15
  • 25
0

yet another way:

with open('yourfilename.txt', 'r') as file:
    words = ' '.join(map(str.rstrip, file))

As you can see from several other answers, file is an iterator, so you can iterate over it and at each loop it will give you a line read from the file (including the \n at the end, that is why we're all stripping it off).

Logically speaking, map applies the given function (i.e. str.rstrip) to each line read in and the results are passed on to join.

Pynchia
  • 10,996
  • 5
  • 34
  • 43