Moving files to subdirectory programatically (without using unix mv command) [duplicate]

StackOverflow https://stackoverflow.com/questions/18399704

  •  26-06-2022
  •  | 
  •  

Question

Is it possible to move by means of os.rename or shutil.move all the files in a directory to a a subdirectory of the same directory?

For example if I have the following structure:

  • Dir_1
    • File_1
    • File_2
    • subDir_1

can I get the following structure:

  • Dir_1
    • subDir_1
      • File_1
      • File_2 ?

Best.-

EDIT: In the end I solved my problem using the following code:

    for fname in os.listdir(src):
      if os.path.isfile(os.path.join(src, fname)):
        os.rename(os.path.join(src, fname), os.path.join(dst, fname))

Thanks a lot to both of you!

Était-ce utile?

La solution

I hope this could help:

import shutil,os,os.path


def walk(top):
    directory = None
    for root, dirs, files in os.walk(top, topdown=False):
        for name in dirs:
            directory = os.path.join(root, name)
        for name in files:
            f1 = os.path.join(root, name)
            if not f1.endswith('.py') and directory:
                shutil.move(f1,directory)


walk(os.path.realpath(os.curdir))

I tried it with this fs tree and it works:

-d/
  |-s/
  |-new file.txt
  |-new file1.txt
  |-move.py
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top