Найти - Пользователи
Полная версия: [Fixed]::Открытие файла по-новой. Как?
Начало » Python для новичков » [Fixed]::Открытие файла по-новой. Как?
1 2
iandriyanov
Подскажите, каким образом, запустив один раз на исполнение код, в котором есть обращение к файлу, и файл имеет название+data_stamp, каждый раз, да хоть раз в минуту или раз в час, файл создавался вновь и все писалось в него. Конкретный пример:


date_stmp = time.strftime("%Y-%m-%d-%H:%M")
with open('out.txt_'+date_stmp, 'a') as f:
                    f.write("\nReceived message '")
                    f.write(data)
                    f.write("' ;")
#                    f.close()
                    f.flush()

Здесь при запуске программы открывается файл с названием out.txt_какая_то_дата, даже если сутки пройдут логи все пишутся и пишутся в него, хотя я пологал что при каждом обращении именно к этому кусочку кода, будет пересоздаваться файл и запись пойдет в новый файл.
FishHook
Весь код покажи
iandriyanov
while True:
    data,addr = UDPSock.recvfrom(buf)
    if data:
        res = simplejson.loads(data)
        if res.get('EVENTID', None) in ["41", "42"]:
            try:
                with get_conn(pool) as con_sel:
                    cur_sel = con_sel.cursor()
                    cur_sel.execute("select sid from users where wiegand26=%s ", (res['CARDNUMBER'], ))
                    sid = cur_sel.fetchone()[0]
                    cur_sel.execute("select id from device where name=%s", (res['POINT'], ))
                    dev_id = cur_sel.fetchone()[0]
                    cur_sel.execute("insert into events(user_sid, device_sid, event_type_id, event_date, add_info) values (%s, %s, %s, %s, %s)", (sid, dev_id, res['EVENTID'], res['DATATIME'], res['DEP'] ))
                    con_sel.commit()
            except Exception as e:
                with open('out.txt_'+date_stmp, 'a') as f:
        #            print "-=-=-=-=\n",e,"\n=-=-=-=-"
        #            import traceback
        #            traceback.print_exc()
                    f.write("\nReceived message '")
                    f.write(data)
                    f.write("' ;")
                    f.close()
#                    f.flush()
            print "\nReceived message '", data,"'"
        else:
#                print("error",res.get('EVENTID', None))
            print "error",res.get('EVENTID', None)
FishHook
Пять раз посмотрел и не нашел, где же определяется загадочная переменная date_stmp
iandriyanov
Первый коммент же?
FishHook
iandriyanov
while True:
    data,addr = UDPSock.recvfrom(buf)
    if data:
        res = simplejson.loads(data)
        if res.get('EVENTID', None) in ["41", "42"]:
            try:
                with get_conn(pool) as con_sel:
                    cur_sel = con_sel.cursor()
                    cur_sel.execute("select sid from users where wiegand26=%s ", (res['CARDNUMBER'], ))
                    sid = cur_sel.fetchone()[0]
                    cur_sel.execute("select id from device where name=%s", (res['POINT'], ))
                    dev_id = cur_sel.fetchone()[0]
                    cur_sel.execute("insert into events(user_sid, device_sid, event_type_id, event_date, add_info) values (%s, %s, %s, %s, %s)", (sid, dev_id, res['EVENTID'], res['DATATIME'], res['DEP'] ))
                    con_sel.commit()
            except Exception as e:
                with open('out.txt_'+date_stmp, 'a') as f:
        #            print "-=-=-=-=\n",e,"\n=-=-=-=-"
        #            import traceback
        #            traceback.print_exc()
                    f.write("\nReceived message '")
                    f.write(data)
                    f.write("' ;")
                    f.close()
#                    f.flush()
            print "\nReceived message '", data,"'"
        else:
#                print("error",res.get('EVENTID', None))
            print "error",res.get('EVENTID', None)
Здесь где она определяется????

iandriyanov
Какая разница где. первый комментарий, это кусок кода. И это кусок кода. Переменная определяется выще в коде.

Ну для наглядности пожалуйте:

import time
date_stmp = time.strftime("%Y-%m-%d-%H:%M")
....
while True:
    data,addr = UDPSock.recvfrom(buf)
    if data:
        res = simplejson.loads(data)
        if res.get('EVENTID', None) in ["41", "42"]:
            try:
                with get_conn(pool) as con_sel:
                    cur_sel = con_sel.cursor()
                    cur_sel.execute("select sid from users where wiegand26=%s ", (res['CARDNUMBER'], ))
                    sid = cur_sel.fetchone()[0]
                    cur_sel.execute("select id from device where name=%s", (res['POINT'], ))
                    dev_id = cur_sel.fetchone()[0]
                    cur_sel.execute("insert into events(user_sid, device_sid, event_type_id, event_date, add_info) values (%s, %s, %s, %s, %s)", (sid, dev_id, res['EVENTID'], res['DATATIME'], res['DEP'] ))
                    con_sel.commit()
            except Exception as e:
                with open('out.txt_'+date_stmp, 'a') as f:
        #            print "-=-=-=-=\n",e,"\n=-=-=-=-"
        #            import traceback
        #            traceback.print_exc()
                    f.write("\nReceived message '")
                    f.write(data)
                    f.write("' ;")
                    f.close()
#                    f.flush()
            print "\nReceived message '", data,"'"
        else:
#                print("error",res.get('EVENTID', None))
            print "error",res.get('EVENTID', None)
FishHook
iandriyanov
Какая разница.
Срифмовать?
Для наглядности. Ты один раз присваиваешь переменной date_stmp значение. ДО ЦИКЛА. С какого суахили ты ждешь, что в этом месте
with open('out.txt_'+date_stmp, ‘a’) as f:
ты будишь получать РАЗНЫЕ значения?
iandriyanov
По тому же суахили, я и пишу сюда! Где косяк?

Вернее где он это понятно. Как рефрешить переменную?
FishHook
Я попробую еще раз.

# -*- coding:utf-8 -*-
import time
import threading
date_stmp = time.strftime("%Y-%m-%d-%H:%M")
def p():
  print 'now=', time.strftime("%Y-%m-%d-%H:%M")
  print 'date_stmp=', date_stmp
t = threading.Timer(70.0, p)
t.start()
now= 2012-07-17-13:39
date_stmp= 2012-07-17-13:38
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB