i have python3 based implementation incoming data checked , end result stored in file fixed name.
with open(filename.tar, 'wb') f: f.write(dumpincomingdata) the filename.tar hard-coded of e.g. incomingfile.tar. problem file keeps getting over-written everytime new incoming data detected , not want. want files written everytime written in different file everytime viz. :
incomingdata1.tarincomingdata2.tar...
how can execute idea in pythonic way?
code snippet
os import chdir path = '/tmp/' filename = 'incomingdata.tar' while true: processes if(condition = true): print("file decoded") chdir(path) open(filename, 'wb') f: f.write(dumpdata) break dumpdata function of module using , shouldn't of concern here.
why not count sequence number until hit free filename?
from itertools import count import os def open_next_file(template='incomingdata{serial}.tar'): filename in (template.format(serial=serial) serial in count()): try: return open(filename, 'xb') except oserror: if not os.path.exists(filename): raise this yield open file filename next available sequence incomingdata0.tar, incomingdata1.tar, , on. operation atomic long os.open(..., o_creat | o_excl) atomic (which is).
for python 2 not support open mode 'x', possible emulate behavior using os.open(..., os.o_creat | os.o_excl). in python 3 mode='xb' sufficient.
Comments
Post a Comment