【问题标题】:Timestamp into output filename时间戳到输出文件名
【发布时间】:2018-04-14 00:59:32
【问题描述】:

我想插入时间戳到 python 脚本的输出文件名中,例如:20011231_230159_md5_filelist.csv

我无法插入代码。

这是脚本的结束,其输出文件名需要有时间戳:

try:

    my_last_data = get_md5(file_full_path) + ", " + get_last_write_time(file_full_path) + ", " + get_size(
        file_full_path) + ", " + file_full_path + "\n"

    with open("md5_filelist.csv", "a") as my_save_file:
        my_save_file.write(my_last_data)

    print(str(file_full_path) + "  ||| Done")

except:
    print("Error On " + str(file_full_path))

这是我正在使用的时间戳代码(虽然不确定它是否是最好的行):

timestr = time.strftime("%Y%m%d_%H%M%S")

我尝试了各种方式插入,都不行。有什么提示吗?

【问题讨论】:

  • 你试过timestr + "md5_filelist.csv"吗?
  • 是的。不起作用。 with open(timestr + "md5_filelist.csv", "a") as my_save_file:
  • 您要修改现有文件的名称还是使用现有文件的时间戳创建一个新文件?
  • 它究竟是如何“不工作”的?
  • 很奇怪。虽然我之前的建议省略了第二个下划线,所以它应该是timestr + "_md5_filelist.csv",但这是一个微不足道的细节。 “不起作用”是什么意思?这很模糊。

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


【解决方案1】:

感谢@pm-2ring(见cmets),解决方法:

timestr = time.strftime("%Y%m%d_%H%M%S")
(timestr + "_md5_filelist.csv", "a")

在脚本中:

try:

    timestr = time.strftime("%Y%m%d_%H%M%S")

    my_last_data = get_md5(file_full_path) + ", " + get_last_write_time(file_full_path) + ", " + get_size(
        file_full_path) + ", " + file_full_path + "\n"

    with open(timestr + "_md5_filelist.csv", "a") as my_save_file:
        my_save_file.write(my_last_data)

    print(str(file_full_path) + "  ||| Done")

except:
    print("Error On " + str(file_full_path))

【讨论】:

    【解决方案2】:

    这就是你所需要的。

    try:
        my_last_data = get_md5(file_full_path) + ", " + get_last_write_time(file_full_path) + ", " + get_size(
            file_full_path) + ", " + file_full_path + "\n"
    
        with open("{}md5_filelist.csv".format(timestr), "a") as my_save_file:
            my_save_file.write(my_last_data)
    
        print(str(file_full_path) + "  ||| Done")
    except:
        print("Error On " + str(file_full_path))
    

    您没有在代码中的任何地方使用 timestr。

    【讨论】:

    • 我收到“C:\x\stby\1\b.txt 错误”,而原始脚本工作正常(但没有为输出文件加上时间戳)。
    猜你喜欢
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多