Python Forum
Convert string to path using Python 2.7 - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Convert string to path using Python 2.7 (/thread-35486.html)

Pages: 1 2


Convert string to path using Python 2.7 - tester_V - Nov-08-2021

Greetings!
I need to find yesterday's modified directories.

but a PC I'm running the code on has Python 2.7 and I cannot use pathlib...
The code I have has a problem (see the error below), I can't get a Path from the string..
"AttributeError: 'str' object has no attribute 'stat'"

I Googled for an answer for about an hour or so but could not find a solution... Confused
Here is the code I got so far:
import os.path
import datetime as dt

tz ='C:\\01'
for dr_name in os.listdir(tz):
    dr_path = os.path.join(tz, dr_name)
    print(type(dr_path)) ## <-- it is alredy a string not Path
    if os.path.isdir(dr_path): 
        print("Directory path name:", dr_path)
        print(type(dr_path))        
        np = os.path.normpath(dr_path) 
        print(type(np))  ## <-- Still string
        yesterday = dt.datetime.now().date() - dt.timedelta(days=1)
        if yesterday == dt.datetime.fromtimestamp(np.stat().st_mtime).date():
            print(f"  Directory modified yesterday -> {np}")
Thank you!


RE: Convert string to path using Python 2.7 - bowlofred - Nov-08-2021

Please try to upgrade to python3.

os.path.* methods are mostly string manipulations. They return paths in the form of a string, not a path object. So after you get the normpath in np, you could gather the stat object with
filestat = os.stat(np)
There is a backport for pathlib to 2.7 in https://pypi.org/project/pathlib2/. I haven't tried it.


RE: Convert string to path using Python 2.7 - tester_V - Nov-09-2021

	
filestat = os.stat(np)
It works but How I can use it ?
It produces an error if I use filestat instead if np in "IF"
Error:
if yesterday == dt.datetime.fromtimestamp(filestat.stat().st_mtime).date():
AttributeError: 'os.stat_result' object has no attribute 'stat'
I wish I could install Python 3.x on the PCs, but they are not under my control... Sad


RE: Convert string to path using Python 2.7 - tester_V - Nov-09-2021

I made changes to the code, I think I'm very close but failing to compare 2(two) time stamps.
yesterday var is formated as YYYY-MM-DD
and the ts var as YYYY-MM-DD HH:MM:SS.milliseconds

for dr_name in os.listdir(tz):
    dr_path = os.path.join(tz, dr_name)
    if os.path.isdir(dr_path): 
        print("Directory path name:", dr_path)       
        yesterday = dt.datetime.now().date() - dt.timedelta(days=1)
        ts = datetime.datetime.fromtimestamp(os.path.getmtime(dr_path))
        print(f" File T_stamp > {ts}")
        if datetime.datetime.fromtimestamp(os.path.getmtime(dr_path)) == yesterday:
            print(f" Yesterday file -> {dr_path}")



RE: Convert string to path using Python 2.7 - bowlofred - Nov-09-2021

In line 5 you start with a datetime (from now()), but then convert it into a date (with .date()).

In line 8 you're comparing a timestamp to a date which won't match. What you might want is to compare the date of that timestamp with your yesterday date.

if datetime.datetime.fromtimestamp(os.path.getmtime(dr_path)).date() == yesterday:
Another preference might be to see if the timestamp lies between two datetime() timestamps.


RE: Convert string to path using Python 2.7 - DeaD_EyE - Nov-09-2021

Chain comparison operators and don't compare if datetimes are equal.

import datetime
import os


def iterdirs(root, min_days_age=0, max_days_age=1):
    now = datetime.datetime.now()

    # not newer than end_date
    end_date = now - datetime.timedelta(days=min_days_age)

    # not older than start_date
    start_date = now - datetime.timedelta(days=max_days_age)

    for path in os.listdir(root):
        if not os.path.isdir(path):
            # if path is not a directory, skip it
            # processing only directories
            continue

        mtime = datetime.datetime.fromtimestamp(os.path.getmtime(path))
        
        # chaining comparison operators:
        # https://www.geeksforgeeks.org/chaining-comparison-operators-python/
        if start_date <= mtime <= end_date:
            yield path



RE: Convert string to path using Python 2.7 - tester_V - Nov-10-2021

Thank you Dead YeY!
I see your point....


RE: Convert string to path using Python 2.7 - tester_V - Nov-20-2021

Greetings to all that work on this Friday night! Wink
I just found I have no idea how to use the snippet Dead YeY shared. Sad
it seems the function name is "iterdir" and if I call it the script errors out...
So,"iterdir" is not function name.
How do I call it?
Is the "root" is my directory to scan?

It looks very elegant but I cannot use it.
 
def iterdirs(root, min_days_age=0, max_days_age=1):
    now = datetime.datetime.now()
 
    # not newer than end_date
    end_date = now - datetime.timedelta(days=min_days_age)
 
    # not older than start_date
    start_date = now - datetime.timedelta(days=max_days_age)
 
    for path in os.listdir(root):
        if not os.path.isdir(path):
            # if path is not a directory, skip it
            # processing only directories
            continue
 
        mtime = datetime.datetime.fromtimestamp(os.path.getmtime(path))
         
        # chaining comparison operators:
        # https://www.geeksforgeeks.org/chaining-comparison-operators-python/
        if start_date <= mtime <= end_date:
            yield path



RE: Convert string to path using Python 2.7 - Gribouillis - Nov-20-2021

tester_V Wrote:if I call it the script errors out...
That's not a good error report for the forum. If there is an error, post at least the complete exception traceback that Python prints on the console.

Also, what is this PC where you can't install Python 3? Get a new one. Python 3 has been around since 2009, and producing Python 2 code is just a waste of time.


RE: Convert string to path using Python 2.7 - ghoul - Nov-20-2021

(Nov-20-2021, 08:51 AM)Gribouillis Wrote: Also, what is this PC where you can't install Python 3? Get a new one. Python 3 has been around since 2009, and producing Python 2 code is just a waste of time.

Probably a work PC or a library or something of that sort....

Indeed writing Python 2 code is a waste of time.