Why truncate when we open a file in 'w' mode in python

前端 未结 8 2107
再見小時候
再見小時候 2020-12-13 05:40

I am going through Zed Shaw\'s Python Book. I am currently working on the opening and reading files chapters. I am wondering why we need to do a truncate, when we are alread

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 06:32

    Scenario:
    I was making a ransomware and needed to encrypt the file, My aim is not to encrypt the complete file but that much only to corrupt it because I want it to be fast in what it does and so saving time in encrypting it all, so I decided to edit some text only.
    Now If I use write then my purpose is destroyed here because I would have to write the file a to z. Then what can I do?
    well here truncate can be put in use.

    Below is my code which just takes a token of last 16 digits in a file:

    with open('saver.txt', 'rb+') as f:
        text_len = len(f.read())
        f.truncate(text_len-16)
        f.close()
    

    I open the file
    Truncate only 16 characters from file which will be replaced by me later.
    Notice I am using it in read only mode, If I use in write mode than File is truncated completely and it will throw error when our truncate command comes in.
    Answering this question after 8.4 years. :)

提交回复
热议问题