syah
syah

Reputation: 3

iterate file in directory and put file with same name into different list

Here i have different kind of files in my directory.

C/Documents

My files:

apple_file1.txt

orange_file2.txt

pear_file1.txt

grape_file2.txt

I would like to put all the files with characters 'file1' and 'file2' into different lists such as 'List1' and 'List2'

My code:

for file in os.listdir(myDir):
    if file.split('_')[-1] in file:
        file1_.append(file)

Upvotes: 0

Views: 188

Answers (2)

mohammed wazeem
mohammed wazeem

Reputation: 1328

You can use something like this

list1 = []
list2 = []
for file in os.listdir(MyDir):
    if file.split('_')[-1].split('.')[0] == 'file1':
        list1.append(file)
    elif file.split('_')[-1].split('.')[0] == 'file2':
        list2.append(file)

Another way of doing this by using glob module. Which provides a function for making file lists from directory wildcard searches.

import glob
import os

os.chdir(MyDir)
list1 = glob.glob("*_file1*")
list2 = glob.glob("*_file2*")

You don't need to change the working directory you can even pass your absolute search path like this

glob.glob("<MyDir>/*_file1*")

Upvotes: 2

Kris
Kris

Reputation: 8868

You can use the glob module to iterate and check the file name to distribute. Something like

import glob
myDir = 'C/Documents'
file_path = myDir+"/*"
files = list(glob.glob(pathname=file_path))
list1 = []
list2 = []
for file in files:
    if file.lower().endswith("file1.txt"):
        list1.append(file)
    else:
        list2.append(file)
##do anything with the lists

Upvotes: 0

Related Questions