fafz
fafz

Reputation: 81

Python group by part of a string

So I'm looking at names of files and some of them have _good and _new suffix at the end. I need to move these files but when I come across a file that has two versions, _good and _new, I only wan the _new files to move.

Here's an example of file names:

student_homework_good
student_homework_new
house_work_good
school_work_good
commute_good

From these files, I don't want student_homework_good to move because student_new exists. The file names are stored in a list: my_files[]

Any suggestions would be welcomed.

Upvotes: 1

Views: 65

Answers (1)

Giorgi Anakidze
Giorgi Anakidze

Reputation: 216

It seems pretty easy. All you need to do, is to check the existence of _new in file name, like

listOfFiles = ['student_homework_new', 'student_homework_good', 'commute_good']
for i in listOfFiles:
    if '_new' in i:
        # code for movement to another directory

Any other _good files will remain in the same directory.

If you only want to group them by names, you could do something like

goodFiles = [i for i in os.listdir('yourdirectory') if '_good' in i]
newFiles  = [i for i in os.listdir('yourdirectory') if '_new' in i]

After grouping, you can move whatever you want to any folder of course.

Upvotes: 1

Related Questions