user7423098
user7423098

Reputation: 321

Modyfying access times of all files in a directory using python

I am a beginner in python and trying to modify access times (touch) of sub-directories and files of a parent directory. I found that how to modify access time of a file here Implement touch using Python?

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

instead of fname above, I want to have sub-directories and files of a parent directory. So I found another question of looping through directories: 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)

Combining code from above examples, I created code:

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)

The code runs without errors, but when I did ls -l, I could not see access time stamp modified. Where am I going wrong? Is the third code correct to touch all files and sub-directories?

I am using python 2.6.

Upvotes: 0

Views: 661

Answers (1)

Ian McGowan
Ian McGowan

Reputation: 3801

Nice use of examples! You're defining a function (touch) in the middle of that for loop, but it's never getting called. One other tip, when starting out sprinkling "print" statements around the script can really help understand what's going on. Also, os.utime takes a string as the first parameter, so there's no point in opening the file, you can skip that part.

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)

It's not a bad idea to isolate the logic for doing the touch into a function (maybe you need to do something more complex in the future?). That would look like:

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)

Upvotes: 1

Related Questions