0

I am trying to sort a result I write into an output file after a certain character ':' by the integer after the character.

First, I tried using sort function but it did not work as it was not a list. I also tried to convert everything to string list and tried to sort accordingly but do not think it’s the most efficient way to go.

NOTE: output file lines are all strings

**Current written output in output_file1.txt:**
hi: 011
hello: 000
hero: 001
You are done!

**Expected written output in output_file1.txt:**
hello: 000
hero: 001
hi: 011
You are done!

Thank you for your help.

Alex Ham
  • 151
  • 1
  • 12
  • You can't sort the file in place with python. You will need to put the entire file into memory to sort it or you can sort it using a `unix` shell. [Sorting a text file alphabetically (Python)](https://stackoverflow.com/questions/27123125/sorting-a-text-file-alphabetically-python) – Error - Syntactical Remorse Apr 16 '19 at 13:40

3 Answers3

1
with open(filepath) as file:
    r = file.readlines()

#splits based on ":" and then sort using the second value ie binary numbers
s = sorted([line.split(":") for line in r[1:-1]], key=lambda x: int(x[1]))

s.insert(0,r[0])
s.append(r[-1])

#Write 's' into File
Preetham
  • 577
  • 5
  • 13
0

I would the insert the lines in order from the very beginning, you can do that efficiently using binary search.

Q: How to compare the current number in the current line with your old file.

Answer:

Case 1: If the maximum number of lines is 111, (in your example you start with 001, I assume you padded with zeros to show how many digits you expect per number) or you now the max number of lines, you can pad with a sufficient number of zeros, then all you have to do is compare you current number with the current last three entries in your line (line[-3:]).

Case 2: You don't know the number of digits:

Sol 2.1: You can try storing a file for words and a file for numbers, and update them in parallel, this will save you from the overhead of Sol 2.2.

Sol 2.2: Split the line by delimiter ':' and get the number (don't forget that you have a space after the delimiter).

That is what I could come up with for now!

Michael Heidelberg
  • 993
  • 11
  • 24
0

As mentioned above, there is no way to sort a file in place.

Regarding your second question, you can use list.sort(key=sort_key). This allows you to supply a method which is applied to every element in your list when comparing the elements for sorting.

In your case you can define a simple function which extracts the last three characters and sort them alphabetically:

def num_sort(x):
   return x[-3:]
your_list.sort(key=num_sort)
fluxens
  • 565
  • 3
  • 15