lucians
lucians

Reputation: 2269

Move file to folders while creating folders

I have some files and I want to move them to some folders. I made the code which create these folders based on number of files. How can I move the files to each folder (better if directly when creating each one) ?

import os
import errno

src = (os.path.expanduser('~\\Desktop\\output8\\singola\\'))

causali = os.listdir(src)
causali.sort(key=lambda x: int(x.split('.')[0]))

for file in enumerate(causali):
    try:
        id_folder = os.makedirs(os.path.expanduser('~\\Desktop\\output8\\singola\\{}'.format(file[0])))
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise

Something like this..

example

Upvotes: 0

Views: 176

Answers (2)

mtkilic
mtkilic

Reputation: 1243

Below code will create sub directory(folder) for each filename in your directory, name of the folders will be same as your filename. And each file will be move to the folder has same name.

import glob, os, shutil                                                                     
source = "C:\\Users\\xx\\Desktop\\Folder"

for file_path in glob.glob(os.path.join(source, '*.*')):
    new_sub_folder = file_path.rsplit('.', 1)[0]
    os.mkdir(os.path.join(source, new_sub_folder))
    shutil.move(file_path, os.path.join(new_sub_folder, os.path.basename(file_path)))

Upvotes: 1

ndrwnaguib
ndrwnaguib

Reputation: 6115

os.rename() or shutil.move(), they both have the same syntax.

os.rename("path/to/current/file.foo", "path/to/new/desination/for/file.foo")
shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")

In your case,

import os
import errno

src = (os.path.expanduser('~\\Desktop\\output8\\singola\\'))

causali = os.listdir(src)
causali.sort(key=lambda x: int(x.split('.')[0]))

for file in enumerate(causali):
   try:
        id_folder = os.makedirs(os.path.expanduser('~/test_move/{}'.format(file[0])))
        os.rename(os.path.expanduser('~\\Desktop\\output8\\singola\\{}'.format(file[1])),os.path.expanduser('~\\Desktop\\output8\\singola\\{}\\{}'.format(file[0],file[1])))
   except OSError as e:path/to/new/destination/for/file
        if e.errno != errno.EEXIST:
            raise

Upvotes: 1

Related Questions