1

I want to read a file, sort text inside the file and overwrite the contents of the file with sorted text.

I have been able to read and sort text, but not sure how to clear contents of the file before writing the sorted text to the file

WL01 = 'Test.txt'
with open(WL01,'r+') as WL:
        lines = WL.readlines()
        lines.sort()
        WL.truncate()
        for line in lines:
            print(line, file = WL)
erukumk
  • 77
  • 8

2 Answers2

2

You are close, just need to return the pointer to the beginning of the file using the seek function, so your code looks like:

WL01 = 'Test.txt'
with open(WL01, 'r+') as WL:
   lines = WL.readlines()
   lines.sort()
   WL.seek(0)  
   WL.truncate()  
   for line in lines:
      WL.write(line)  
mario ruiz
  • 880
  • 1
  • 11
  • 28
1

you can use the truncate() method with a size of 0 and after calling truncate(0), the file pointer will be at the end of the file, so it is necessary to use the seek(0) method to move the file pointer back to the beginning of the file before writing the sorted text!

check this out:

WL01 = 'Test.txt'
with open(WL01, 'r+') as WL:
    lines = WL.readlines()
    lines.sort()
    WL.truncate(0) #clear the contents of the file!!!
    WL.seek(0)  #move the file pointer to the beginning of the file
    for line in lines:
        WL.write(line)
Freeman
  • 9,464
  • 7
  • 35
  • 58
  • Please link to the documentation so we can read about that. – Kelly Bundy Aug 24 '23 at 13:23
  • And I just tried it, it [didn't work](https://ato.pxeger.com/run?1=lZHPbsIwDMa1a5_C1Q5pBKvgNiHxBj0i9ZxljhqpiivHqPAsXLjAQ-1plrRsCIkLvvnP95M_-3QdjtJROJ8ve3Efnz9v1DarNWxB7TBKLQdRRTF66YAGDFVuLkGNSoOJ0DabAlI4YrDgAyhH9GVYzeUcA_sglV2C8z1u20Y_ofEjbZb0Pkoa0E8Fi0dF7wPGtHPb1Izme0orfW_VkVhuhTQjvA_WCFYrDe-2R8MgHYKlIBgkArkpzxuXZfnvMKOyyQl5d5iAI_tEy_XX7c13v53_7w2_). – Kelly Bundy Aug 24 '23 at 13:25
  • What comments of yours are you referring to? I only see one (and it'll likely get deleted soon). – Kelly Bundy Aug 24 '23 at 13:31
  • @KellyBundy Firstly, why are you chatting down here? You can send all your messages in one. Secondly, it's enough to kindly give a friendly reminder, there is no need for arguing or debating! – Freeman Aug 24 '23 at 13:35