[Python] python os.utime() call failing with a permission error even though the file being...

Discussão em 'Python' iniciado por Stack, Julho 29, 2025.

  1. Stack

    Stack Membro Participativo

    I have a bunch of files that were backed up to a usb drive using the cp -r command without specifying to preserve timestamp. (Dumb mistake, I know). However, most of these files have a certain header from which can be read the date (in UTC) when the file was created. I would like to set the modified timestamp of these files to the local version of that timestamp (which happens to be UTC-07:00).

    But my python script to do this is failing with Permission error.

    PermissionError: [Errno 1] Operation not permitted


    The only thing I can think of that would cause this is that the file being modified is on a usb drive that is mounted as /media/myname/backup/... But I don't see why that should matter.

    Moreover, using the touch -t command, I am able to change the timestamp of this file without permission errors. But when run from a python script I get the error.

    This is the code:

    obs_date = str(HeaderItemsOfInterest(hdr))
    utc_time = datetime.fromisoformat(obs_date)
    utc_timestamp = utc_time.timestamp()
    local_timestamp = utc_timestamp - tucson_offset
    local_time = datetime.fromtimestamp(local_timestamp)
    print(f"{p}:")
    print(f" UTC_time:{obs_date} ==>")
    print(f" MST_time:{local_time}")

    os.utime(p, (int(local_timestamp), int(local_timestamp)))


    The last line causes the error.

    And this is the output including error output:

    /media/scohen/backup/stellarmate/Pictures/Betelgeuse/Light/Betelgeuse_Light_001.fits:
    UTC_time:2025-01-18T02:07:22.703 ==>
    MST_time:2025-01-17 19:07:22.703000
    Traceback (most recent call last):
    File "/usr/lib/python3.12/idlelib/run.py", line 580, in runcode
    exec(code, self.locals)
    File "/home/scohen/python/fits/fitsredater.py", line 83, in <module>
    process_directory(item)
    ^^^^^^^^^^^^^^^^^^^^^^^
    File "/home/scohen/python/fits/fitsredater.py", line 50, in process_directory
    process_file(item)
    File "/home/scohen/python/fits/fitsredater.py", line 41, in process_file
    localize_date(p)
    File "/home/scohen/python/fits/fitsredater.py", line 35, in localize_date
    os.utime(p, (int(local_timestamp), int(local_timestamp)))
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    PermissionError: [Errno 1] Operation not permitted


    And here is the directory listing of the file I am trying to change:

    $ ll
    total 2416
    drwxrwxrwx 2 1000 1000 4096 Jul 27 14:56 ./
    drwxrwxrwx 3 1000 1000 4096 Jul 27 14:56 ../
    -rwxrwxrwx 1 1000 1000 2465280 Jan 17 2025 Betelgeuse_Light_001.fits*

    Continue reading...

Compartilhe esta Página