fff
fff

Reputation: 111

join one word lines in a file

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)

Upvotes: 1

Views: 97

Answers (5)

Pynchia
Pynchia

Reputation: 11590

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.

Upvotes: 0

Raydel Miranda
Raydel Miranda

Reputation: 14360

You can also use list comprehensions:

whole_string = " ".join([word.strip() for word in file])
print(whole_string)

Upvotes: 2

Zack Tanner
Zack Tanner

Reputation: 2590

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

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

Upvotes: 1

Chad S.
Chad S.

Reputation: 6633

This is I think what you want..

' '.join(l.strip() for l in file)

Upvotes: 0

TerryA
TerryA

Reputation: 59974

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

Upvotes: 1

Related Questions