colidom
colidom

Reputation: 83

How to move and rename multiple files to a specific folder?

I have a small problem with a tool I built in Python.

This tool works classifying files by filenames and making folders by a word in every filename and then moving all the files to the corresponding folder.

Files:

Actual results:

Code Version 1.0

#!/usr/bin/python3
# v1.0
# Importing  modules
import os
import shutil
import sys

# Path of input and output files
src = input('Input files: ')
dest = input('Destination files: ')

os.chdir(dest)

def classify():
    for f in os.listdir(src):
        splitname = f.split('_')
        status = splitname[1]
        topic = splitname[2]
        foldername = topic + '_' + 'Status_' + status
        if not os.path.exists(foldername):
            os.mkdir(foldername)
        shutil.move(os.path.join(src, f), foldername)

print('Sorting out files, please wait...')
classify()
print('¡DONE!')

Improvement

But in the v2.0 I would like to "improve" it a little more, just keeping the same usability but changing filenames from original name to "Message_*.xml" and it works but only moving one file, not all of them.

Current results:

Expected results:

Code Version 2.0

#!/usr/bin/python3
# v2.0
# Importing  modules
import os
import shutil
import sys

# Path of input and output files
src = input('Input files: ')
dest = input('Destination files: ')

os.chdir(dest)

def classify():
    for f in os.listdir(src):
        splitname = f.split('_')
        status = splitname[1]
        topic = splitname[2]
        foldername = topic + '_' + 'Status_' + status
        newFileName = foldername + '\\' + 'Message_' + '.xml'
        if not os.path.exists(foldername):
            os.mkdir(foldername)
        shutil.copy(os.path.join(src, f), newFileName)

print('Sorting out files, please wait...')
classify()
print('¡DONE!')

Upvotes: 2

Views: 301

Answers (1)

Matt M
Matt M

Reputation: 710

You are naming everything Message_ so you will never get multiple files. You need to parse the names in the folder and then increment the filenames accordingly.

msgName = 'Message_0'
newFileName = foldername + '\\' + msgName + '.xml'
if not os.path.exists(foldername):
    os.mkdir(foldername)
else:
    while os.path.isfile(newFileName) is True:
        msgInt = int(msgName[8:])
        msgInt += 1
        msgName = msgName[:8] + str(msgInt)
        newFileName = foldername + '\\' + msgName + '.xml'    
shutil.copy(os.path.join(src, f), newFileName)

Now if you already have message_0.xml in your folder, you will get a message_1.xml instead, and so on.

Upvotes: 2

Related Questions