【问题标题】:Modyfying access times of all files in a directory using python使用python修改目录中所有文件的访问时间
【发布时间】:2017-06-08 16:41:24
【问题描述】:

我是 python 的初学者,正在尝试修改父目录的子目录和文件的访问时间 (touch)。我在这里找到了如何修改文件的访问时间Implement touch using Python?

import os
def touch(fname, times=None):
    with open(fname, 'a'):
        os.utime(fname, times)

我想拥有父目录的子目录和文件,而不是上面的fname。于是又发现了循环遍历目录的另一个问题:Iterating through directories with Python

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print os.path.join(subdir, file)

结合以上示例中的代码,我创建了代码:

import os
rootdir = '/usr/sf/adir'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        fname = os.path.join(subdir, file)
        def touch(fname, times=None):
            with open(fname, 'a'):
                os.utime(fname, times)

代码运行没有错误,但是当我执行ls -l 时,我看不到访问时间戳被修改。我哪里错了?第三个代码对touch所有文件和子目录是否正确?

我正在使用 python 2.6。

【问题讨论】:

  • 你为什么用9岁的Python版本?
  • 您的方法 touch 已定义但从未调用。您是否可能将代码错误地复制到您的问题中?

标签: python


【解决方案1】:

很好地使用示例!您在 for 循环的中间定义了一个函数(触摸),但它永远不会被调用。另一个提示,当开始在脚本周围散布“打印”语句时,真的可以帮助理解正在发生的事情。另外,os.utime 的第一个参数是字符串,所以打开文件没有意义,你可以跳过那部分。

import os
rootdir = 't3'
print("Checking "+rootdir)

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        fname = os.path.join(subdir, file)
        print("touching "+fname);
        os.utime(fname, None)

将进行触摸的逻辑隔离到一个函数中并不是一个坏主意(也许您将来需要做一些更复杂的事情?)。看起来像:

import os

def touch(file):
    print("touching "+file);
    os.utime(file, None)

rootdir = 't3'
print("Checking "+rootdir)

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        fname = os.path.join(subdir, file)
        touch(fname)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-31
    • 2022-08-22
    • 2020-11-17
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    相关资源
    最近更新 更多