简体   繁体   English

Python覆盖包含当前日期和时间的文件

[英]Python overwrite file containing current date and time

I am new to Python. 我是Python的新手。 I need to create a door.lock file that contains the current date and time. 我需要创建一个包含当前日期和时间的door.lock文件。 Also, I need to overwrite this file every x minutes with a new file containing the current date and time. 另外,我需要每隔X分钟用一个包含当前日期和时间的新文件覆盖此文件。 I'm using this as a pseudo lock file to allow me to test on run of the software whether or not the software crashed and how long ago it crashed. 我将此文件用作伪锁定文件,以使我能够在软件运行时进行测试,以了解该软件是否崩溃以及崩溃多久了。 My issue is I can't seem to overwrite the file. 我的问题是我似乎无法覆盖该文件。 I've only failed at creating and/or appending the file. 我只是在创建和/或附加文件失败。 I created the following as a test: 我创建了以下内容作为测试:

    from datetime import datetime, timedelta

    ending = False

    LOCK_FILENAME = "door.lock"  # The lock file
    LOCK_FILE_UPDATE = True
    MINS_LOCK_FILE_UPDATE = 1  # the (x) time in minutes to write to lock file
    NEXT_LOCK_FILE_UPDATE = datetime.now()

    lock_file = open(LOCK_FILENAME, "w")
    now = datetime.now()
    NOW_STRING1 = str(now.strftime("%Y-%m-%d_%a_%H:%M"))
    lock_file.write(NOW_STRING1)
    print "First Now String"
    print NOW_STRING1

    # ==============================================================================
    #Main Loop:
    while ending is False:

    # ==============================================================================
      # Check if it is time to do a LOCK FILE time update
      now = datetime.now()
      NOW_STRING1 = str(now.strftime("%Y-%m-%d_%a_%H:%M"))
      if LOCK_FILE_UPDATE:  # if LOCK_FILE_UPDATE is set to True in DM settings
        if NEXT_LOCK_FILE_UPDATE <= datetime.now():
            lock_file.write(NOW_STRING1)
            print NOW_STRING1
            NEXT_LOCK_FILE_UPDATE = datetime.now() + timedelta(minutes=MINS_LOCK_FILE_UPDATE)

Will someone pinpoint my error(s) for me? 有人会为我指出我的错误吗? TIA TIA

When I cat the above file, door.lock, it is empty. 当我整理以上文件door.lock时,它是空的。

You need to push buffer to file. 您需要将缓冲区推送到文件。 You can do it with a close() and re-open for next write. 您可以使用close()然后重新打开以进行下一次写入。

lock_file.close()
...
lock_file = open(LOCK_FILENAME, "a")

If you are logging events you'd be better using a logger instead of a plain text file. 如果要记录事件,最好使用记录器而不是纯文本文件。

Solution from @MAC will work except it will append and seems that you don't want to do that so just open again with the 'w' option or yet better, use the 'w+' option so it can be truncated (which for what I get it is what you want to do) and read. @MAC的解决方案将起作用,除了它会追加,而且似乎您不想这样做,因此只需再次使用'w'选项打开,或者更好的是,使用'w +'选项以便将其截断(针对什么)我知道这是您想要做的)并阅读。

Also, consider your changes won't get written down until you close the file (having said that, consider open/close inside your loop instead). 另外,请考虑您的更改在关闭文件之前不会被记录下来(话虽如此,请考虑在循环内部打开/关闭)。

lock_file = open(LOCK_FILENAME, "w+")
now = datetime.now()
NOW_STRING1 = str(now.strftime("%Y-%m-%d_%a_%H:%M"))
lock_file.write(NOW_STRING1)
# your loop and so on ...
lock_file.close()

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

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