Python 2.7 – Script to rename _TMP folder

Question:

I try to create a script to rename some folder with "_TMP" lasts digits

import os
basedir = 'E:Test'
for fn in os.listdir(basedir):
  if not os.path.isdir(os.path.join(basedir, fn)):
    continue # Not a directory
  if '_TMP' not in fn:
    continue # Invalid format
    firstname = fn.rpartition('_TMP')
    os.rename(os.path.join(basedir, fn),os.path.join(basedir, firstname))

Hello everybody. I am trying to rename a list of folders which are numbered
Example:
1
2_TMP
3
50_TMP

Looking at other codes I create this one. But I get the error:

os.rename(os.path.join(basedir, fn),os.path.join(basedir, firstname))
  File "C:Python27libntpath.py", line 67, in join
 p_drive, p_path = splitdrive(p)
  File "C:Python27libntpath.py", line 116, in splitdrive
  normp = p.replace(altsep, sep)
 AttributeError: 'tuple' object has no attribute 'replace'

Can you help me? I searched the internet for the error but found nothing to help me.
Thank you

Asked By: NicolaIta

||

Answers:

The function rpartition returns a tuple object with substrings.

fn = '1_TMP'
filename = fn.rpartition('_TMP')

The variable filename stores a tuple object ('1', '_TMP', ''). You need to access the desired string object inside the tuple e.g. filename[0]

Answered By: Phantom
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.