代码之家  ›  专栏  ›  技术社区  ›  Iliyas Momin

如何在文本文件中获得python脚本输出,而不覆盖当前的一个文本文件

  •  0
  • Iliyas Momin  · 技术社区  · 2 年前

    您好,我已经编写了由任务调度器运行的python代码。此代码删除超过5天的文件夹。代码运行良好,但我在日志文本文件中获取了该代码的输出。只要代码运行,现有的日志文件就会被覆盖。我想看看每一个日程记录,现在不可能了。 如何每次在不同的文件中或在同一个文件中获得代码输出,而不覆盖数据。

    import os
    import sys
    import datetime
    import shutil
    path=r"C:\Users\Iliyas\OneDrive\Documents"
    all_dir=os.listdir(path)
    age=5
    today=datetime.datetime.now()
    for each_dir in all_dir:
        each_dir_path=os.path.join(path,each_dir)
        if os.path.isdir(each_dir_path):
           die_cre_date=datetime.datetime.fromtimestamp(os.path.getctime(each_dir_path))
           dif_days=(today-die_cre_date).days
           if dif_days > age:
               print(f' The {each_dir_path} folder in older the {dif_days} days, deleting it:')
               shutil.rmtree(each_dir_path)
               print("path deleted")
           else:
               print("there is nothing delete older than 5 days")
               break
    

    这段代码由。任务调度器中的bat文件

    D:\Python\python.exe D:\Code\Delete_Files_older_than_5_days.py > D:\code\Log\Delete_data_log.txt
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   Varun P    2 年前

    您需要使用“>>”将正常的“标准输出”附加到文件。
    D:\Python\python.exe D:\Code\Delete_Files_older_than_5_days.py > D:\code\Log\Delete_data_log.txt