friends. I’m stucked with a problem and I appreciate some help. I’m coding a Python program that will search an entire directory tree and iterate over files to find those that was accessed for the last time more than a certain time ago like more than two years ago.
I’m working with pathlib com accomplish this task. The problem is that I have some paths that has special chars and somes white spaces and it’s leading me to a FileNotFoundError.
Here is an example:
# -*- coding: utf-8 -*-
from pathlib import Path
path = r"E:\MY DIR\#SOME_DIR\#SOME_SUBDIR\ANOTHER_SUBDIR\firstname.lastname\AppData\Local\Packages\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\AC\#!001\MicrosoftEdge\Cache\LJ53QTBW\FaktCyrWeb-Normal-0038c5aa5c3243bb2995139e9aeb9519f62f098d0e0f7fab6c8b655a292d857d[1].woff"
print(Path(path).stat().st_atime)
Like I said, the code above raises an FileNotFoundError exception.
Is there a way to accomplish this? To make Python access this path?
I think that Windows does not accept path with more 256 characters: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#maximum-path-length-limitation
Try this:
#/usr/bin/python3
# -*- coding: utf-8 -*-
import os
from pathlib import Path
def longpath(path):
regular = os.fspath(path.resolve())
if not regular.startswith('\\\\?\\'):
regular = '\\\\?\\' + regular
return Path(regular)
path = Path(r"E:\MY DIR\#SOME_DIR\#SOME_SUBDIR\ANOTHER_SUBDIR\firstname.lastname\AppData\Local\Packages\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\AC\#!001\MicrosoftEdge\Cache\LJ53QTBW\FaktCyrWeb-Normal-0038c5aa5c3243bb2995139e9aeb9519f62f098d0e0f7fab6c8b655a292d857d[1].woff")
path_long = longpath(path)
print(Path(path_long).stat().st_atime)