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
#11
(Nov-20-2021, 01:15 AM)tester_V Wrote: So,"iterdir" is not function name.
How do I call it?
Is the "root" is my directory to scan?
Code from DeaD_EyE will yield contend so most iterate over or eg call list() on it.
Yes root is directory to scan.
Add os.chdir(root) or get error if not run code is same folder as files.

Here test Python 3.9 and Python 2.7 works fine in both.
# iter_d.py
import datetime
import os

def iterdirs(root, min_days_age=0, max_days_age=30):
    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)
    os.chdir(root)
    for path in os.listdir(root):
        if not os.path.isdir(path):
            # if path is not a directory, skip it
            # processing only directories
            continue

        #print(path)
        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

if __name__ == '__main__':
    root = r'G:\div_code'
    # Make a list
    lst = list(iterdirs(root))
    # Iterate over content
    for d in iterdirs(root):
        print(d)
Output:
# Python 3.9 G:\div_code\answer λ python iter_d.py answer pack_tut # Python 2.7 G:\div_code\answer λ py -2.7 iter_d.py answer pack_tut
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  convert string to float in list jacklee26 6 1,812 Feb-13-2023, 01:14 AM
Last Post: jacklee26
  how to convert tuple value into string mg24 2 2,233 Oct-06-2022, 08:13 AM
Last Post: DeaD_EyE
  -i option changes sys.path (removes leading empty string '') markanth 6 1,897 Aug-26-2022, 09:27 PM
Last Post: markanth
  Convert string to float problem vasik006 8 3,269 Jun-03-2022, 06:41 PM
Last Post: deanhystad
  Convert a string to a function mikepy 8 2,421 May-13-2022, 07:28 PM
Last Post: mikepy
Question How to convert string to variable? chatguy 5 2,225 Apr-12-2022, 08:31 PM
Last Post: buran
  Convert string to int Frankduc 8 2,394 Feb-13-2022, 04:50 PM
Last Post: menator01
  WebDriverException: Message: 'PATH TO CHROME DRIVER' executable needs to be in PATH Led_Zeppelin 1 2,148 Sep-09-2021, 01:25 PM
Last Post: Yoriz
  Convert each element of a list to a string for processing tester_V 6 5,166 Jun-16-2021, 02:11 AM
Last Post: tester_V
Question convert unlabeled list of tuples to json (string) masterAndreas 4 7,352 Apr-27-2021, 10:35 AM
Last Post: masterAndreas

Forum Jump:

User Panel Messages

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