Python Forum
Convert string to path using Python 2.7
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert string to path using Python 2.7
#1
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!
Reply
#2
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.
Reply
#3
	
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
Reply
#4
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}")
Reply
#5
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.
Reply
#6
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
snippsat and tester_V like this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#7
Thank you Dead YeY!
I see your point....
Reply
#8
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
Reply
#9
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.
tester_V likes this post
Reply
#10
(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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  WebDriverException: Message: 'PATH TO CHROME DRIVER' executable needs to be in PATH Led_Zeppelin 1 635 Sep-09-2021, 01:25 PM
Last Post: Yoriz
  Convert each element of a list to a string for processing tester_V 6 1,587 Jun-16-2021, 02:11 AM
Last Post: tester_V
Question convert unlabeled list of tuples to json (string) masterAndreas 4 3,012 Apr-27-2021, 10:35 AM
Last Post: masterAndreas
  Convert String of an int array to a Numpy array of ints mdsousa 5 2,143 Apr-08-2021, 08:00 PM
Last Post: mdsousa
  Convert string to JSON using a for loop PG_Breizh 3 1,212 Jan-08-2021, 06:10 PM
Last Post: PG_Breizh
  Convert hex value into string Sancho_Pansa 8 1,781 Dec-23-2020, 08:54 AM
Last Post: Sancho_Pansa
  convert string into multiple columns in python3 VAN 2 1,440 Sep-26-2020, 11:14 PM
Last Post: scidam
  ValueError: could not convert string to float: RandomCoder 3 2,812 Jul-27-2020, 07:38 AM
Last Post: ndc85430
  could not convert string to float player1681 4 3,827 May-22-2020, 12:10 PM
Last Post: buran
  String to File Path creedX 4 1,505 Apr-06-2020, 07:29 PM
Last Post: creedX

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020