简体   繁体   中英

How do you use open() with appending mode AND seek() in Python on Linux?

I have the following:

with open(file, 'a') as log:

   #A bunch of code, some of it writes to log.

   log.seek(0)
   log.write(time.strftime(t_format))

seek() doesn't work with append, and if I use 'w', then the beginning of the file gets overwritten. In the docs it says, "...'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)"

Is there any way to override this?

The second argument to seek allows seeking relative to the end of the file:

with open(filename, 'w') as log:
    log.seek(0, 0)
    log.write(time.strftime(t_format))

You should also consider using Python's logging module to write logs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM