Search code examples
pythonpython-3.xbatch-rename

Python3 batch rename


I'm new in python and trying to make script, which renames all files in directory by this pattern ShowName + SeasonNumber + EpisodeNumber This script gets filename as argv[1] and directory as argv[2]. Then in find_needed_parts it parses string and returns number of seasone, episode and show name. But this script is droping with such traceback:

Traceback (most recent call last):
  File "/home/usrname/Documents/renameFiles/main.py", line 38, in <module>
    main()
  File "/home/usrname/Documents/renameFiles/main.py", line 35, in main
    os.rename(pathAndFilename, os.path.join(dir, rename_name))
  File "/usr/lib/python3.5/posixpath.py", line 89, in join
    genericpath._check_arg_types('join', a, *p)
  File "/usr/lib/python3.5/genericpath.py", line 143, in _check_arg_types
    (funcname, s.__class__.__name__)) from None
TypeError: join() argument must be str or bytes, not 'builtin_function_or_method'

And here is the code:

#!/usr/bin/python3


import glob
import os
import sys
import re


def find_needed_parts(filename):
    ep_reg = re.search("(E|e)(\d+)", filename)
    if ep_reg:
        found_ep = ep_reg.group(2)
    s_reg = re.search("(S|s)(\d+)", filename)
    if s_reg:
        found_s = s_reg.group(2)
    ext_reg = re.search("\.(\w+)", filename)
    if ext_reg:
        ext = ext_reg.group(1)
    body_reg = re.search("((^(.*?)([^E0-9])+)|(^(.*?)([^e0-9])))", filename)
    if body_reg:
        body = body_reg.group(1)
    return body, found_ep, found_s, ext


def main():
    filename = sys.argv[1]
    direct = sys.argv[2]
    body, ep, s, ext = find_needed_parts(filename)
    pattern = "*." + ext

    for pathAndFilename in glob.iglob(os.path.join(direct, pattern)):
        title, ext = os.path.splitext(os.path.basename(pathAndFilename))
        ep = int(ep) + 1  # type: int
        rename_name = str(body + 'S' + s + 'E' + str(ep) + '.' + ext)
        os.rename(pathAndFilename, os.path.join(dir, rename_name))


main()

UPD1. here are the params

argv[1] = abcd E01 S09 ockoeko ko k.avi
argv[2] = .

Solution

  • the main problem is in the statement

    os.rename(pathAndFilename, os.path.join(dir, rename_name))
    

    where you are using dir built-in function, when you've probably meant

    os.rename(pathAndFilename, os.path.join(direct, rename_name))