简体   繁体   中英

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()

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 (ie 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))

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM