qemu-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [PATCH v2 28/38] qapi/gen.py: update write() to be more idiomatic


From: Eric Blake
Subject: Re: [PATCH v2 28/38] qapi/gen.py: update write() to be more idiomatic
Date: Fri, 25 Sep 2020 10:47:18 -0500
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Thunderbird/68.11.0

On 9/25/20 8:52 AM, Markus Armbruster wrote:

This was my best attempt to open the file read/write, creating it if it
doesn't exist.

Plain

         f = open(pathname, "r+", encoding='utf-8')

fails instead of creates, and

         f = open(pathname, "w+", encoding='utf-8')

truncates.

If you know a better way, tell me!

IIUC, you need  "a+" as the mode, rather than "w+"

Sure this lets me do

             f.seek(0)
             f.truncate(0)
             f.write(text)

to overwrite the old contents on all systems?

As long as you do a single pass over the output (you issue a stream of f.write() after the truncate, but never a seek), then this will work.


Documentation cautions:

     [...] 'a' for appending (which on some Unix systems, means that all
     writes append to the end of the file regardless of the current seek
     position).

Yes, that means that random access is impossible on such a stream. But not all file creation patterns require random access.

--
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3226
Virtualization:  qemu.org | libvirt.org




reply via email to

[Prev in Thread] Current Thread [Next in Thread]