0

I have question regarding moving one file in each sub directories to other new sub directories. So for example if I have directory as it shown in the image

enter image description here

And from that, I want to pick only the first file in each sub directories then move it to another new sub directories with the same name as you can see from the image. And this is my expected result

enter image description here

I have tried using os.walk to select the first file of each sub directories, but I still don't know how to move it to another sub directories with the same name

path = './test/'
new_path = './x/'

n = 1
fext = ".png"

for dirpath, dirnames, filenames in os.walk(path): 
    for filename in [f for f in filenames if f.endswith(fext)][:n]:
        print(filename) #this only print the file name in each sub dir

The expected result can be seen in the image above

Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

0

You are almost there :)

All you need is to have both full path of file: an old path (existing file) and a new path (where you want to move it).

As it mentioned in this post you can move files in different ways in Python. You can use "os.rename" or "shutil.move".

Here is a full tested code-sample:

import os, shutil

path = './test/'
new_path = './x/'

n = 1
fext = ".png"

for dirpath, dirnames, filenames in os.walk(path): 
    for filename in [f for f in filenames if f.endswith(fext)][:n]:
        print(filename) #this only print the file name in each sub dir

        filenameFull = os.path.join(dirpath, filename)
        new_filenameFull = os.path.join(new_path, filename)

        # if new directory doesn't exist - you create it recursively
        if not os.path.exists(new_path):
            os.makedirs(new_path)        

        # Use "os.rename"
        #os.rename(filenameFull, new_filenameFull)

        # or use "shutil.move"
        shutil.move(filenameFull, new_filenameFull)
VictorDDT
  • 583
  • 9
  • 26