Removing Characters from a Folder Name

251
4
Jump to solution
12-09-2019 09:15 AM
PaulGardiner
New Contributor III

So I originally had a query relating to moving a pdf map to a separate folder which is named with the pdf name.

Johannes Bierer provided the code below (which works perfectly):

import glob, os, shutil
from shutil import copyfile

inPath = r"yourPath"
outPath = r"yourPath"

for file in glob.glob(os.path.join(inPath, "*.pdf")):

    outFolder = os.path.basename(file[:-4])

    if os.path.isdir(os.path.join(outPath, outFolder)):
        shutil.rmtree(os.path.join(outPath, outFolder))
    else:
        pass
       
    outDir = os.mkdir(os.path.join(outPath, outFolder))
   
    outDir1 = os.path.join(outPath, outFolder)
   
    outFile = os.path.join(outDir1, os.path.basename(file))
       
    copyfile(file, outFile)

My follow up query to this is what should be added to the above code in order that the first 12 characters of the file name are removed when naming the folder?

 

E.g. the file name is 'Species_Map 12_HH_132'. I would like the folder to be called '12_HH_132'.

Wasn't sure whether this should be appended to the original question or not.

0 Kudos
2 Solutions

Accepted Solutions
DanPatterson_Retired
MVP Esteemed Contributor
'Species_Map 12_HH_132'[12:]
'12_HH_132'‍‍

slice it off

'Species_Map 12_HH_132'.split(" ")[1]
'12_HH_132'

split it off

View solution in original post

DanPatterson_Retired
MVP Esteemed Contributor

I presume this is where you are getting your filename

outFolder = os.path.basename(file[:-4])

which would mean

outFolder = os.path.basename(file[:-4])[12:]  # using the slice example

View solution in original post

4 Replies
DanPatterson_Retired
MVP Esteemed Contributor
'Species_Map 12_HH_132'[12:]
'12_HH_132'‍‍

slice it off

'Species_Map 12_HH_132'.split(" ")[1]
'12_HH_132'

split it off

PaulGardiner
New Contributor III

Is it possible to work this in to the code written Johannes? 

I'm using the code to batch move c. 300 maps at a time to separate folders so it would help if it could be integrated into the process. 

0 Kudos
DanPatterson_Retired
MVP Esteemed Contributor

I presume this is where you are getting your filename

outFolder = os.path.basename(file[:-4])

which would mean

outFolder = os.path.basename(file[:-4])[12:]  # using the slice example

PaulGardiner
New Contributor III

Perfect, thank you.

0 Kudos