-1

I would like to use Python to rename the files in a directory called myShow from a .txt file that contains the "target" names:

realNameForEpisode1
realNameForEpisode2
realNameForEpisode3

The hierarchy looks like:

episodetitles.txt
myShow
├── ep1.m4v
├── ep2.m4v
└── ep3.m4v

I tried the following:

import os

with open('episodetitles.txt', 'r') as txt:
    for dir, subdirs, files in os.walk('myShow'):
        for f, line in zip(sorted(files), txt):

            originalName = os.path.abspath(os.path.join(dir, f))
            newName = os.path.abspath(os.path.join(dir, line + '.m4v'))
            os.rename(originalName, newName)

but I don't know why I get a ? at the end of the filename before the extension:

realNameForEpisode1?.m4v
realNameForEpisode2?.m4v
realNameForEpisode3?.m4v
Vivek Jha
  • 257
  • 2
  • 10
  • What didn't work? Try placing some print statements in your code or use a debugger to see the values of f, originalName, newName etc. Get to a place that you know works (like placing a file in the same directory and testing that you can rename it.) This is something you should be able to troubleshoot your way through with just a little additional effort on your part. – SteveJ Dec 03 '17 at 04:59
  • Sorry, forgot to add that I have tested it, but don't understand why a `?` appears before the extension. Is it because the text file has `\n` at the end of each line? – Vivek Jha Dec 03 '17 at 06:03

2 Answers2

0

Just import 'os' and it will work:

import os
with open('episodes.txt', 'r') as txt:
    for dir, subdirs, files in os.walk('myShow'):
        for f,line in zip(sorted(files), txt):
            if f == '.DS_Store':
               continue
            originalName = os.path.abspath(os.path.join(dir, f))
            newName = os.path.abspath(os.path.join(dir, line + '.m4v'))
            os.rename(originalName, newName)
Vijesh
  • 795
  • 3
  • 9
  • 23
0

I figured it out - it was because in .txt files, the final character is an implicit \n, so needed to slice the filename to not include the last character (which became a ?):

import os


def showTitleFormatter(show, numOfSeasons, ext):
    for season in range(1, numOfSeasons + 1):

        seasonFOLDER = f'S{season}'
        targetnames = f'{show}S{season}.txt'

        with open(targetnames, 'r') as txt:
            for dir, subdirs, files in os.walk(seasonFOLDER):
                for f, line in zip(sorted(files), txt):

                    assert f != '.DS_Store'

                    originalName = os.path.abspath(os.path.join(dir, f))
                    newName = os.path.abspath(os.path.join(dir, line[:-1] + ext))
                    os.rename(originalName, newName)
Vivek Jha
  • 257
  • 2
  • 10