Rama
Rama

Reputation: 1069

Python: How to continue writing on the same line in a file?

Here is a snippet:

f = open("a.txt","r")
paragraph = f.readlines()
f1 = open("o.txt","w")
for line in paragraph:
    f1.write(line)

Here, how can I manage to write continuosly on the same line in o.txt?
For example, a.txt:

Hi,   
how  
are   
you?

Then o.txt should be:

Hi, how are you?

Thanks in advance.

Upvotes: 2

Views: 6440

Answers (5)

Rama
Rama

Reputation: 1069

I found a solution. Here it goes. Basically using the replace().

f = open("a.txt","r")
paragraph = f.readlines()
f1 = open("o.txt","w")
for line in paragraph:
    line = line.replace("\n"," ")
    f1.write(line)

Other methods are welcome! :)

Upvotes: 0

Zinob
Zinob

Reputation: 103

This occurs because Python reads the entire line, including the new-line character represented as \n in python. The string in your example would result in an array like:

['Hi,\n', 'how\n', 'are\n', 'you?']

To solve this you need to remove the trailing \n from each line, but beware that the last line might not contain a \n so you cant just remove the last character of each line. There are pre-made methods built in to python to help you remove white-space characters (like new-line \n and space " ") from the beginning and the end of a string.

The official documentation can be a bit daunting, but finding and using information from documentation is probably one of the most important skills in the field of computing. Look at the official documentation and see if you find any useful methods in the string class. https://docs.python.org/3/library/stdtypes.html#str.strip

Upvotes: 0

user3278460
user3278460

Reputation:

remove new line char using rstrip

f = open("a.txt","r")
paragraph = " ".join(map(lambda s: s.rstrip('\n'), f.readlines()))
f1 = open("b.txt","w")
f1.write(paragraph)

Upvotes: 2

MC93
MC93

Reputation: 799

try:
    with open('a.txt') as in_fh, open('o.txt', 'w') as out_fh:
        out_fh.write(' '.join(in_fh.read().split('\n')))
except IOError:
    # error handling

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107287

You need to strip the lines then join and write to file :

with open("a.txt","r") as in_f,open("o.txt","w") as out_f: 
    out_f.write(' '.join(in_f.read().replace('\n','')))

Also as a more pythonic way for use with statement to dealing with files.

Or better :

with open("a.txt","r") as in_f,open("o.txt","w") as out_f: 
    out_f.write(' '.join(map(str.strip(),in_f))

or use a list comprehension :

with open("a.txt","r") as in_f,open("o.txt","w") as out_f: 
    out_f.write(' '.join([line.strip() for line in in_f])

Upvotes: 2

Related Questions