How to open (read-write) or create a file with truncation allowed?

前端 未结 4 1625
無奈伤痛
無奈伤痛 2020-12-09 07:29

I want to:

  • open a file in read-write mode if it exists;
  • create it if it doesn\'t exist;
  • be able to truncate it anytime-anywhere.
4条回答
  •  既然无缘
    2020-12-09 08:28

    Well, there are only these modes, and all of them have the "defects" you listed.

    Your only option is to wrap open(). Why not something like this? (Python)

    def touchopen(filename, *args, **kwargs):
        open(filename, "a").close() # "touch" file
        return open(filename, *args, **kwargs)
    

    it behaves just like open, you could even rebind it to open() if you really wish.

    all of open's features are preserved, you can even do:

    with touchopen("testfile", "r+") as testfile:
        do_stuff()
    

    You could of course create a contextmanager which opens the file in a+ mode, reads it into memory, and intercepts writes so you handle truncation by magically creating a temporary file in w mode, and renames that tempfile to your original file when you close it, but that would be overkill I guess.

提交回复
热议问题