D.j D.j - 4 days ago 5
Python Question

How to access files from a subfolder that lies into a folder which recently created or modified using python?

I am performing web test automation using selenium Webdriver. I am pretty much new to python and Web test. The question is : I want to write a Python code that automatically opens the files in following way:

"C:\Software\" this path has many folders like

C:\Software\
AB_101_B1\
AB_101_B1\
*.bin
*.hex
*.hex
AB_101_B1.zip

AB_101_B2\
AB_101_B2\
*.bin
*.hex
*.hex
AB_101_B2.zip

AB_102_B1\
AB_102_B1\
*.bin
*.hex
*.hex
AB_102_B1.zip
...

AB_103_B7\
AB_103_B7\
*.bin
*.hex
*.hex
AB_103_B1.zip


Here AB_103_B7 is latest created or modified folder. Each folder contains one subfolder with same name as main folder(eg:AB_103_B7) and one ZIP folder (AB_103_B7.zip). The subfolder and ZIP folder contains 3 files with different extensions(Example: .bin, .hex , .hex)

I want to access latest modified or created folder then automatically upload files from this subfolder and also upload zip folder into Website.

Note: The main folder "AB_* " keeps updating. So code must detect the latest folder either by name or by modified time.
I could directly upload file by setting directory, Example:
driver.find_element_by_id('abc').send_keys("C:\software\AB_103_B7\AB_103_B7\test.bin")
.
But my problem is to access the latest folder.

Could any help me with coding in python? I checked
os.walk()
from other questions. I am confused about what should be written for dirname, subdirs, files.

Answer

Try this code and let me know in case of any issues:

import os
path = "C:\\Software\\"
latest_modified_folder = ''
time_of_modification = 0

for root, subdirs, files in os.walk(path):
    for subdir in subdirs:
        if os.path.getmtime(os.path.join(root, subdir)) > time_of_modification:
            time_of_modification = os.path.getmtime(os.path.join(root, subdir))
            latest_modified_folder = os.path.join(root, subdir)

for file_ in os.listdir(latest_modified_folder):
    # I'm not sure about how you want to upload all files from folder, so...
    driver.find_element_by_id('abc').send_keys(os.path.join(latest_modified_folder, file_))  
Comments