Search code examples
pythonquicksortreadlines

Formatting .txt file before usage of readlines()


Because I need to sort a .txt file with quicksort, I used readlines() to use my function. The problem is that it isn't formatted like before the usage of readlines().

f = open(filename)
array = f.readlines()

Then I used my quicksort function.

How the Input File looks like:

12.01.2020 bcd
05.02.1990 efd
13.04.1992 cba

How it should look like after quicksort:

05.02.1990 efd
13.04.1992 cba
12.01.2020 bcd

but in my code it's looking like this:

'05.02.1990\tefd\n', '13.04.1992\tcba\n', '12.01.2020\tbcd\n'

Any Suggestions how i can correct my usage of readlines()?


Solution

  • This is actually how readlines is used. It generates a list of strings that are found in your text file. As you can see each string is separated by a ,, the tabs are represented as \t and the new line is represented as \n.

    You can simply write the array to a file again to get the wanted output.

    with open('sorted.txt', 'w') as of:
        for s in sorted:
            of.write(s)
    

    PS. what you're printing is the content of your output list, this will replace things like tabs and newline characters with their unicode representation. If you loop through your output and print the content, you'll see the output that you want to see.

    for s in output:
        print(s)