Solution 1

def sort_lines(filepath, sorting='asc'):
    with open(filepath, "r") as f:
        read_data = f.readlines()
    if sorting == 'asc':
        read_data.sort()
    else:
        read_data.sort(reverse=True)
    with open(filepath, "w") as f:
        for line in read_data:
            f.write(line)

Sort Lines in Text File

Write a function that receives the path to a text file and sorts all the
lines in the file ascending or descending, depending on the 'sorting'
parameter.

Example:

sort_lines('file1.txt', sorting='asc')
sort_lines('file1.txt', sorting='desc')

Test Cases

test asc order - Run Test

import tempfile

def test_asc_order():
    fp = tempfile.NamedTemporaryFile(mode="w")
    fp.write('line 3\n')
    fp.write('line 1\n')
    fp.write('line 2\n')
    fp.write('line 4\n')
    fp.flush()
    
    sort_lines(fp.name)

    with open(fp.name) as fp:
        assert fp.readlines()[0] == 'line 1\n'
        fp.seek(0)
        assert fp.readlines()[1] == 'line 2\n'

test desc order - Run Test

import tempfile

def test_desc_order():
    fp = tempfile.NamedTemporaryFile(mode="w")
    fp.write('line 3\n')
    fp.write('line 1\n')
    fp.write('line 2\n')
    fp.write('line 4\n')
    fp.flush()
    
    sort_lines(fp.name, sorting='desc')

    with open(fp.name) as fp:
        assert fp.readlines()[0] == 'line 4\n'
        fp.seek(0)
        assert fp.readlines()[1] == 'line 3\n'
def sort_lines(filepath, sorting='asc'): pass