Q:

How can i append a text file to order the contents

I have a text file with about 2000 numbers, they are written to the file in a random order...how can i order them from within python? Any help is  appreciated
file = open('file.txt', 'w', newline='')
s = (f'{item["Num"]}')
file.write(s + '\n')
file.close()
read = open('file.txt', 'a')
sorted(read)

A:

You need to:

read the contents of the file: open('file.txt', 'r').read().
split the content using a separator: separator.split(contents)
convert each item to a number, otherwise, you won't be able to sort numerically: int(item)
sort the numbers: sorted(list_of_numbers)

Here is a code example, assuming the file is space separated and that the numbers are integers:
import re 
file_contents = open("file.txt", "r").read() # read the contents
separator = re.compile(r'\s+', re.MULTILINE) # create a regex separator
numbers = []
for i in separator.split(f): # use the separator
    try:
        numbers.append(int(i)) # convert to integers and append
    except ValueError: # if the item is not an integer, continue
        pass
 sorted_numbers = sorted(numbers)

You can now append the sorted content to another file:
with open("toappend.txt", "a") as appendable:
    appendable.write(" ".join(sorted_numbers)

