Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Take contents of a file, convert them to a single line and append them to the original file Python

I’m working on solving a task that requires that I open a text file in Python. The file has 3 lines:

Moose
Chases
Car

I need to read that file, then append the three words concatenated on the 4th line. So, the modified text file would contain:

Moose
Chases
Car
Moose Chases Car

I’m new to working with files, so I am not sure why what I am doing is not modifying the file.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def func(value):
    return ''.join(value.splitlines())

f = open("WordTextFile1.txt", "a+")
myString = f.read()
new_str = func(myString)
f.write(new_str)
f.close

Any assistance is greatly appreciated.

>Solution :

Try this.

def func(value):
    return  '\n' + ' '.join(value.splitlines()) 

with open("abc.txt", "r+") as f:
    data = func(f.read())
    
    f.write(data)



When you read the file in the a+ mode, it actually returns nothing.


Or you can seek to the start of file before reading it. when using a+ mode.

def func(value):
    return  '\n' + ' '.join(value.splitlines()) 

with open("abc.txt", "a+") as f:
    f.seek(0)
    data = func(f.read())
    f.write(data)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading