Python file listing

Viewed 95

I'm trying to find all the files in a folder starting with 'msCam' and ending with an extension '.avi'. I manage to do so with the following code:

path = path_to_analyze
files = [i for i in os.listdir(path) if os.path.isfile(os.path.join(path,i)) and \
         'msCam' in i]
print(len(files))
for file in files:
        if file.endswith(".avi"):
            msFileList = [os.path.join(path, file)]
            print(msFileList)

But this stores only the last file found in the given 'msFileList' variable.

print(msFileList)

How can I pass all the files to be stored?

View the output here

3 Answers
path = path_to_analyze
files = [i for i in os.listdir(path) if os.path.isfile(os.path.join(path,i)) and \
     'msCam' in i]
msFileList = [] #create and empty list
print(len(files))
for file in files:
    if file.endswith(".avi"):
        msFileList.appened(os.path.join(path, file)) #append result to list

print(msFileList)

Does this do what you are looking for?

filepath = './'
matching_files = []
with os.scandir(filepath) as entries:
    for entry in entries:
        if entry.name.startswith('msCam') and entry.name.endswith('.avi'):
            matching_files.append(entry.path+entry.name)

Your list is overwritten with the latest value in every iteration. You have to use the inbuilt .append() method.

path = path_to_analyze
files = [i for i in os.listdir(path) if os.path.isfile(os.path.join(path,i)) and \
         'msCam' in i]
print(len(files))

msFileList = [] # filenames will be appended in this list
for file in files:
        if file.endswith(".avi"):
            msFileList.append(os.path.join(path, file)) # using .append()
            # print(msFileList)

print(msFileList) # Whole List will be printed
Related