TransWikia.com

Check if string in path and do something

Stack Overflow Asked on December 18, 2021

Im trying to check if a word is inside a path and if True do something but it always returns False.

For example, my main path is C:/Users/aka/Desktop/Imagenes and some of the subfolders and files are:

C:/Users/aka/Desktop/Imagenes/Show
C:/Users/aka/Desktop/Imagenes/Show/geo
C:/Users/aka/Desktop/Imagenes/Other/geo/ha.jpg
C:/Users/aka/Desktop/Imagenes/Other
C:/Users/aka/Desktop/Imagenes/Other/ramdomfiles
C:/Users/aka/Desktop/Imagenes/Other/ramdomfiles/lo.jpg

and with this function I want to do somthing but only with the paths that contains the string Other for example, but it always go to the else statement and gives me File in folder: Show File in folder: Other any ideas on how can I make this work ?

def generate_tree(path,string):
    text=''
    for file in os.listdir(path):
        rel = path + "/" + file
        print(rel)
        if  string in rel and os.path.isdir(rel):   
            text += ' Main folder: ' +file
            text += generate_tree(rel,string)
        else:
            text += ' File in folder: '+file
    return text

2 Answers

You need to add .split('/') after rel in the if statement.

def generate_tree(path,string):
    text=''
    for file in os.listdir(path):
        rel = path + "/" + file
        print(rel)
        if  string in rel.split('/') and os.path.isdir(rel):   
            text += ' Main folder: ' +file
            text += generate_tree(rel,string)
        else:
            text += ' File in folder: '+file
    return text

Answered by Sabito 錆兎 on December 18, 2021

I believe your problem is here:

rel = path + "/" + file

I'm guessing you're on Windows, where the path delimiter is a backslash. For better results, try this:

rel = os.path.join(path, file)

Answered by Basil on December 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP