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

Time:12-10

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.

CodePudding user response:

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)

CodePudding user response:

Here is the code

You've to open the file in wither r or w mode in order to do both read and write operation on a file.

with open('asfa.txt', 'r ') as file:
    lines = file.read().splitlines()
    string = ' '.join(lines)
    file.write('\n'   string)

output

Moose
Chases
Car
Moose Chases Car
  • Related