简体   繁体   English

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

[英]How to create multiple files with different name in Python

I need create multiple files with different names but I recive data each seconds then I need save this data in each file with diferent names but my only code makes a file and when you receive another data this over write the existing file and not create another. 我需要创建多个具有不同名称的文件,但我每秒都会获取数据,然后需要将此数据保存在具有不同名称的每个文件中,但是我唯一的代码创建了一个文件,当您收到另一个数据时,这会覆盖现有文件,而不创建另一个文件。

This is my code: 这是我的代码:

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)

Move these lines inside the get_json function: 将这些行get_json函数中:

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

As it stands now, filename is only calculated once, when you start this script. 就目前而言,启动此脚本时, filename仅计算一次。 You need to do it each time you're going to save a file. 每次要保存文件时都需要这样做。

This is the answer: 这是答案:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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