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