Kiya229
Kiya229

Reputation: 63

How do I move both files and folders to the specified directory?

There is a code that moves files from one directory to another, but it doesn't move folders.

import os,glob
import shutil

inpath = str5
outpath = str6

os.chdir(inpath)
for file in glob.glob("*.*"):

    shutil.move(inpath+'/'+file,outpath)

How to make it move both files and folders to the specified directory?

Upvotes: 2

Views: 47

Answers (2)

cyborg
cyborg

Reputation: 594

You can use os.listdir to get all the files and folders in a directory.

import os
import shutil

def move_file_and_folders(inpath, outpath):
    for filename in os.listdir(inpath):
        shutil.move(os.path.join(inpath, filename), os.path.join(outpath, filename))

In your case,

inpath = <specify the source>
outpath = <specify the destination>
move_file_and_folders(inpath, outpath)

Upvotes: 1

Ananth
Ananth

Reputation: 4407

*.* selects files that have an extension, so it omits sub-folders.

Use * to select files and folders.

Then you should see your desired result.

for file in glob.glob("*"):
    shutil.move(inpath+'/'+file,outpath)

Upvotes: 1

Related Questions