Solution 1

def write_string(filepath, a_string, overwrite_all=False):
    if overwrite_all:
        with open(filepath, "w") as f:
            f.write(a_string + "\n")
    else:
        with open(filepath, "a") as f:
            f.write(a_string + "\n")

Write String to File Optional Overwrite

Write a function that receives a path to a text file as first parameter,
a string and an optional "ovewrite_all" boolean.
If overwrite_all is false, the function should
append the string at the end of current content in the text file.
If it's true, it should clean the content in the file and
write only given string.

There should always be a new line char at the end of the written line.
See test cases for more details.

Example:

write_string('test-file.txt', 'this is the string', overwrite_all=False)

Test Cases

test write string with overwrite - Run Test

import tempfile

def test_write_string_with_overwrite():
    fp = tempfile.NamedTemporaryFile(mode="w")
    fp.write('this is line 1\n')
    fp.write('this is line 2\n')
    fp.write('this is line 3\n')
    fp.flush()
    
    write_string(fp.name, 'my name is john', overwrite_all=True)

    with open(fp.name) as fp:
        assert len(fp.readlines()) == 1
        fp.seek(0)
        assert fp.readlines()[0] == 'my name is john\n'

test write string no overwrite - Run Test

import tempfile

def test_write_string_no_overwrite():
    fp = tempfile.NamedTemporaryFile(mode="w")
    fp.write('this is line 1\n')
    fp.write('this is line 2\n')
    fp.write('this is line 3\n')
    fp.flush()
    
    write_string(fp.name, 'my name is john')

    with open(fp.name) as fp:
        assert len(fp.readlines()) == 4
        fp.seek(0)
        assert fp.readlines()[3] == 'my name is john\n'
def write_string(filepath, a_string, overwrite_all=False): pass