Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python 2.7 – Script to rename _TMP folder

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

os.rename(os.path.join(basedir, fn),os.path.join(basedir, firstname))
  File "C:\Python27\lib\ntpath.py", line 67, in join
 p_drive, p_path = splitdrive(p)
  File "C:\Python27\lib\ntpath.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

>Solution :

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]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading