0

I have let's say 5 directories, let's call them dir1, dir2, dir3, dir4, dir5.

These are all in the current directory. Each of them contains 1 files called title.mkv. I want to rename the files to the directory name they are in, ie the file title.mkv in dir1, I want to rename to dir1.mkv.

I also want to then move the file to another folder. What python tools do I need for this besides os and glob?

  • Possibly `shutil.move()` if you don't want to use `os.rename()` http://stackoverflow.com/questions/8858008/moving-a-file-in-python – Green Cell Sep 03 '15 at 01:46

3 Answers3

0

If you have the full filename and directory, to rename the files, you can use

import os
f_name = 'E:/temp/nuke.mkv'
# Removes '/' at the end of string
while f_name.endswith('/'):
    f_name = f_name[:-1]
# Generates List Containing Directories and File Name
f_name_split = f_name.split('/')
f_path = ''
# Iterates Through f_name_split, adding directories to new_f_path
for i in range(len(f_name_split)-1):
    f_path += f_name_split[i] + '/'
# Makes New Name Based On Folder Name
new_name = f_name_split[-2] + '.mkv'
# Gets The Old File Name
f_name = f_name_split[-1]
# Renames The File
os.rename(f_path + f_name, f_path + new_name)

To go through all of the directories, you could do it recursively, have the system output it to a file [windows: dir /s /b /a > file.txt], or use os.walk. To move a file, you can use os.rename(source, destination)

SuperNova
  • 138
  • 8
0

The following should work, although you will have problems if there is more than one file per source folder:

import os 

source_folder = r"c:\my_source_folder"
target_folder = r"c:\target_folder"

for directory_path, dirs, files in os.walk(source_folder):

    # Current directory name
    directory = os.path.split(directory_path)[1]

    # Ensure only MKV files are processed
    files = [file for file in files if os.path.splitext(file)[1].lower() == '.mkv']

    # Rename each file

    for file in files:
        source = os.path.join(directory_path, file)
        target = os.path.join(target_folder, directory + ".mkv")

        try:
            os.rename(source, target)
        except OSError:
            print "Failed to rename: {} to {}".format(source, target)

It will search all sub folders from the source folder and use the current folder name for the target name.

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
0

The following function uses shutil.move, which moves across filesystem and has overwrite protection in case destination file exists. File name can be relative.

from os.path import basename, dirname, isfile, abspath, splitext
from shutil import move

def rename_to_dirname_and_move(name, dst, overwrite=False, verbose=False):

    """renames 'name' to its directory name, keeping its extension
       intact and moves to 'dst' directory across filesystem
    """
    if not isfile(name):
        raise ValueError("{} is not a file or doesn't exist".format(name))

    abs_name = abspath(name)
    dir_name = basename(dirname(abs_name))
    new_name = '{}{}'.format(dir_name, splitext(name)[1])
    dst_name = os.path.join(dst, new_name)

    if not overwrite and isfile(dst_name):
        raise OSError('file {} exists'.format(dst_name))

    try:
        move(abs_name, dst_name)
    except Exception as e:
        print("Can't move {} to {}, error: {}".format(abs_name, dst_name,e))
    else:
        if verbose:
            print('Moved {} to {}'.format(abs_name, dst_name))
Nizam Mohamed
  • 8,751
  • 24
  • 32