2 回答

TA貢獻1909條經驗 獲得超7個贊
您可以查看該文件是否已經存在并稍等一下
while True:
timestr = time.strftime("%Y%m%d%H%M%S")
if not os.path.exists(timestr):
break
time.sleep(.1)
with open(timestr, "wb") as myfile:
mydata = ET.tostring(orders_data)
myfile.write(mydata)
您不必等待,只需添加幾秒鐘即可。如果您每秒處理大量文件,這將導致文件名在時間上向前漂移。
mytime = time.time()
while True:
timestr = time.strftime("%Y%m%d%H%M%S", time.localtime(mytime))
if not os.path.exists(timestr):
break
time.sleep(.1)
with open(timestr, "wb") as myfile:
mydata = ET.tostring(orders_data)
myfile.write(mydata)
另一種選擇是在循環之前獲取單個時間戳并隨時更新它。
mytime = time.strftime("%Y%m%d%H%M%S")
for index, row in enumerate(reader):
....
mytime = f"mytime-{index}"
....

TA貢獻1890條經驗 獲得超9個贊
每次運行循環時更改變量名稱,我建議使用 with 語句打開文件,因為打開文件后還必須關閉它
with open(timestr, 'wb') as myfile: myfile.write(mydata)
編輯:我能想象到你的代碼中唯一的缺陷是打開文件后沒有關閉文件
添加回答
舉報