在单独的文件中同时写入最后修改日期的文件名

时间:2019-06-18 06:58:24

标签: python python-3.x

对于我的项目,我想将目录中存在的文件名及其最后修改日期存储在单独的日志文件中。

我想到了一种方法,首先将目录中的文件名附加到list1,然后将修改日期附加到list2,然后将两个列表同时写入日志文件?我只是想问问这些方法中最好的方法是什么,或者还有其他优雅的方法吗?还是他们可以使用任何直接方法?谢谢

同时打印2个列表的代码:

a=[file1,file2]
b=[date1,date2]

col_format = "{:<5}" * 2 + "\n"

with open("log.txt", 'w') as of:
    for x in zip(a, b):
        of.write(col_format.format(*x))

2 个答案:

答案 0 :(得分:0)

您可以使用字典:

d = {file1: date1, file2: date2}

col_format = "{:<5}" * 2 + "\n"  

with open("log.txt", 'w') as of:
    for file in d:
        of.write(col_format.format(file, d[file]))

或使用元组的单个列表(如@kantal建议):

a = [(file1, date1), (file2, date2)]

col_format = "{:<5}" * 2 + "\n"  

with open("log.txt", 'w') as of:
    for tup in a:
        of.write(col_format.format(tup[0], tup[1]))

或者,只需简单地同时写入名称和日期,而不存储它们。像这样:

col_format = "{:<5}" * 2 + "\n" 

with open("log.txt", 'w') as of:
    for file in os.listdir():
        of.write(col_format.format(file, os.path.getmtime(file))

答案 1 :(得分:0)

此代码也对我有用

该程序将最后修改日期的文件名写入单独的文件

import os
import time
from datetime import datetime

col_format = "{:<35}" * 2 + "\n"

with open("log.txt", 'w') as of:

    for file in os.listdir("path to directory"):
        mtime = os.path.getmtime(file)
        of.write(col_format.format(file, time.ctime(mtime)))
相关问题