Lilly H-M
Lilly H-M

Reputation: 1

How do you turn multiple lines of text in a file into one line of text in python?

I have a text file with a number value on every line and I am trying to condense all the values onto a single line with a space between them. This is what I have so far but it's not working:

for line in f1:
    line = line.rstrip('\n')
    f2.write(line)

f1.close()
f2.close()

Upvotes: 0

Views: 1413

Answers (3)

pcurry
pcurry

Reputation: 1414

If you are in Python 2.7+ or Python 3.x, and the size of the file is not prohibitive, you could probably do it in memory:

with open(filename1, 'r') as fin, open(filename2, 'w+') as fout:
    lines = fin.readlines()
    cleaned = [line.strip() for line in lines]
    joined = ' '.join(cleaned)
    fout.write(joined)

Upvotes: 1

L3viathan
L3viathan

Reputation: 27273

Just print them with a space inbetween:

...

for i, line in enumerate(f1):
    space = " " if i != 0 else ""
    line = line.rstrip('\n')
    f2.write(space + line)

f1.close()
f2.close()

If the files aren't huge (i.e. they fit in memory), an easier way would be:

with open("foo") as f1, open("bar", 'w') as f2:
    f2.write(" ".join(line.rstrip('\n') for line in f1))

Upvotes: 4

Netwave
Netwave

Reputation: 42678

This will do:

with open("f1", "r") as f1:
    with open("f2", "w") as f2:
        f2.write(" ".join(map(lambda x: x.strip("\n"), f1.readlines())))

Take all lines form f1, strip the "\n", join them with " " and write that string to the new file.

Upvotes: 0

Related Questions