Home > Back-end >  remove all argument from a list that start with a letter
remove all argument from a list that start with a letter

Time:11-17

i have a problem with python list: in the file I have to insert a function that takes as argument a path of a folder and that returns a list of strings with the complete path of the image files inside the folder that I go to specify, excluding all images whose file name does not start by number. I wrote this code but I can’t get it to work. Any advice? (image files are of two types or numbers as names, or start with 'r', but I should make a generic function for each letter!) '''

import os
import numpy as np


def funzione(folder: str) -> list:
    files = []
    for (root, dirs, file) in os.walk(folder):
        for f in file:
            if f.startswith("r"):
                pass
            else:
                files.append(os.path.join(root, f):
                print(np.shape(file))
                return file

if __name__ == '__main__':
    path = './data/fruits/training/Pear 2'
    print(funzione(folder=path))

'''

CodePudding user response:

Several issues:

import os
import numpy as np


def funzione(folder: str) -> list:
    files = []
    for (root, dirs, file) in os.walk(folder):
        for f in file:
            if f.startswith("r"): # <- if else not needed. use not f.startswith('r')
                pass
            else:
                files.append(os.path.join(root, f): # <- missing append closure )
                print(np.shape(file))
                return file # <- stops the for loop after one iteration

if __name__ == '__main__':
    path = './data/fruits/training/Pear 2'
    print(funzione(folder=path))

How it should look like:

import os
import numpy as np


def funzione(folder: str) -> list:
    files = []
    for root, dirs, file in os.walk(folder):
        for f in file:
            if not f.startswith("r"):
                files.append(os.path.join(root, f)):
                print(np.shape(file))
    return files

if __name__ == '__main__':
    path = './data/fruits/training/Pear 2'
    print(funzione(folder=path))

you can use a tuple of values as argument for the startswith method like:

f.startswith(('a', 'b', 'c', ..., 'z', '1', ...))

It will work like an or if starts with 'a' or 'z'...

  • Related