【问题标题】:Writing a list of creation time of items in a folder编写文件夹中项目的创建时间列表
【发布时间】:2015-03-20 18:25:05
【问题描述】:

我正在尝试编写一个文本文件,其中包含目录中每个文件的创建日期。我看了this 问题,但我仍然需要帮助,除了好奇为什么下面的代码不起作用。

我想我已经接近了。它适用于 文件夹 的创建日期,但我想知道 文件 的创建时间。

import os, os.path, time, datetime    
mydir = '/home/user/ebay/'
mydir2 = '/home/user/'
def writefiles():
    with open(mydir2 + '/items.txt', "wb") as a:
        for path, subdirs, files in os.walk(mydir):
            for file in files:
                a.write(file+' , '+(time.ctime(os.path.getctime(file))) + os.linesep)
writefiles()

我收到此错误消息:

OSError: [Errno 2] No such file or directory: 'PkV20ZrzMs'

这很奇怪,因为有一个名为“PkV20ZrzMs”的文件。我尝试添加目录位置,但没有任何区别。

我认为我接近的原因是,当我将(os.path.getctime(file) 更改为(os.path.getctime(path) 时,我得到了文件夹的创建日期,如下所示:

PkV20ZrzMs , Fri Mar 20 13:43:31 2015
qZzo0ZUAtm , Fri Mar 20 13:43:31 2015
Tm5f8Lhgcd , Fri Mar 20 13:43:31 2015
vgMCBGdJu0 , Fri Mar 20 13:43:31 2015
Ja7Bwa5uEi , Fri Mar 20 13:43:31 2015

【问题讨论】:

  • 您是否为files 中的每个file 添加了带有os.path.join(dirpath, file) 的目录位置?
  • 是的,我刚才又试了一次。它不能解决问题。

标签: python-2.7 datetime timestamp


【解决方案1】:

以下内容对我有用,所以也许你的路径有问题?请注意,mydir2 中有一个尾部斜杠,这可能会在您连接 '/items.txt' 时弄乱您正在写入的路径。

import os, os.path, time, datetime    

mydir = '/home/xnx/temp'
mydir2 = '/tmp'

def writefiles():
    with open(mydir2 + '/items.txt', "wb") as a:
        for path, subdirs, files in os.walk(mydir):
            for file in files:
                a.write(file+' , '+(time.ctime(os.path.getctime(
                           os.path.join(path, file)))) + os.linesep)
writefiles()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-22
    • 2018-02-09
    • 1970-01-01
    • 2017-01-09
    • 2014-04-20
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多