Mason
Mason

Reputation: 303

Use relative path to get all png files in python

Trying to retrieve all the paths of the pngs in different sub folders.

All sub folders are located within a main folder - logs.

pngs = []

for idx, device in enumerate(udid):
    pngs += glob.glob(os.getcwd() + "/logs/" + device + "_" + get_model_of_android_phone(device) + "/" + "*.png")

File structure

logs/123456789_SM-G920I/123456789google_search_android.png

The values in bold will change. I have added in *.png for the changing pngs.

But how do i get the paths of the pngs when i do not have an absolute path to the png file?

Update

get_model_of_android_phone(device) is a method to get the following value here.

E.g. 123456789_SM-G920I

I am thinking to remove it cause it is not really working as intended. Would like to replace the method with something like *

Upvotes: 0

Views: 2414

Answers (2)

Nishu Tayal
Nishu Tayal

Reputation: 20860

You can use following in simplified way to get all file names:

for name in glob.glob(os.getcwd() + "/logs/**/*.png", recursive=True):
    print '\t', name

When recursive is set, ** will matches 0 or more subdirectories when followed by a separator.

If you just want to make list, use the following code snippet :

pngs = glob.glob(os.getcwd() + "/logs/**/*.png", recursive=True)

It will return a list of all png file paths.

Reference : https://docs.python.org/3/library/glob.html

Upvotes: 2

Lê Tư Thành
Lê Tư Thành

Reputation: 1083

for idx, device in enumerate(udid):
    path_device = os.getcwd() + "/logs/" + device + "_" + get_model_of_android_phone(device) + "/"
    file_list = os.listdir(path_device)
    pngs = [path_device+file_png for file_png in file_list if str(file_png).endswith(".png")]

Upvotes: 1

Related Questions