4

I am having a strange issue with python when I try to change the "Date Modified" field value in Windows. Specifically, if I write to the file and then try to change its Date Modified attribute, the change fails (the Date Modified becomes the time I ran the python script). However, if I don't write to the file (if I comment out the out.write function call) the Date Modified time is correctly set to 11/2017.

The Date Accessed time is set as expected in both situations.

Below is my code (python 2.7):

import os
import time
import datetime

out = open("out.test", "wb")
#comment out the write line to get this to work
out.write("hi")
out.flush()
out.close

fileLocation = "out.test"
year = 2017
month = 11
day = 5
hour = 19
minute = 50
second = 0

date = datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute, second=second)
modTime = time.mktime(date.timetuple())

os.utime(fileLocation, (modTime, modTime))

Interestingly, if I use a separate python process (i.e. run python in another cmd prompt) to alter the Date Modified, that also works as well.

Is there some other flush-like function I need to call in order to properly set the Date Modified time if I write to the file?

Thanks in advance.

1 Answer 1

3

The problem lies in this faulty line:

out.close

this doesn't close the file (it does nothing useful, just reading the reference of the function, and not calling it). Normally not a big deal because python closes files on exit, but not here.

When the process terminates/the file handle is garbage collected, an implicit close is called on the file, which sets the modification date to current time.

So utime changes the time when file is open, but the file is closed afterwards, and the modification time is reset: it seems to have no effect.

(a similar issue has been asked & answered here: system vs call vs popen in Python)

The fix is of course:

out.close()

Note that there's a subtle difference when writing or not to the file. If you don't write to the file, the implicit close call probably doesn't have to update the file time, which explains that it works.

Final advice: use context managers to avoid issues like that. You won't have to call close so often:

with open("out.test", "w") as out:
    out.write("hi")
    out.flush()

# file is closed when exiting "with" block
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.