如何在Python中创建具有不同名称的多个文件

时间:2017-06-30 05:38:11

标签: python python-2.7 python-3.x

我需要创建具有不同名称的多个文件,但我每秒都会收到数据,然后我需要在每个文件中保存这些数据,但是我的唯一代码会生成一个文件,当您收到另一个数据时,这会覆盖现有文件而不是创造另一个。

这是我的代码:

name= datetime.utcnow().strftime('%Y-%m-%d %H_%M_%S.%f')[:-3]
   filename = "Json/%s.json"% name

def get_json():
    if not os.path.exists(os.path.dirname(filename)):
                try:
                    os.makedirs(os.path.dirname(filename))
                except OSError as exc: # Guard against race condition
                    if exc.errno != errno.EEXIST:
                        raise 
    with open(filename, "w") as f:
                f.write("Hello")

def net_is_up():
    while(1):
        response = os.system("ping -c 1 " + hostname)
        if response == 0:
            print "[%s] Network is up!" % time.strftime("%Y-%m-%d %H:%M:%S")
            #read_json()
            get_json()

        else: 
            print "[%s] Network is down :(" % time.strftime("%Y-%m-%d %H:%M:%S")

        time.sleep(60)

2 个答案:

答案 0 :(得分:2)

将这些行移到get_json函数中:

name = datetime.utcnow().strftime('%Y-%m-%d %H_%M_%S.%f')[:-3]
filename = "Json/%s.json"% name

现在,当您启动此脚本时,filename仅计算一次。每次要保存文件时都需要这样做。

答案 1 :(得分:1)

这就是答案:

def get_json():
    name= datetime.utcnow().strftime('%Y-%m-%d %H_%M_%S.%f')[:-3]
    filename = "Json/%s.json"% name
    if not os.path.exists(os.path.dirname(filename)):
                try:
                    os.makedirs(os.path.dirname(filename))
                except OSError as exc: # Guard against race condition
                    if exc.errno != errno.EEXIST:
                        raise 
    with open(filename, "w") as f:
                f.write("Hello")

def net_is_up():
    while(1):
        response = os.system("ping -c 1 " + hostname)
        if response == 0:
            print "[%s] Network is up!" % time.strftime("%Y-%m-%d %H:%M:%S")
            #read_json()
            get_json()

        else: 
            print "[%s] Network is down :(" % time.strftime("%Y-%m-%d %H:%M:%S")

        time.sleep(60)