user6178025
user6178025

Reputation:

removing a string of four characters from the front and thirteen characters from the end of a filename

I have seen the basic Python code for a filename replacement in a directory but they are always for known strings, but how would you remove random characters of a certain length?

Would this work?

newFileName = file.replace([-5:], "")

As I am trying to remove the last five characters from the filename without removing the extension.

Here is an update: I am trying to do this:

DMC-CIWS15-AAAA-A00-00-0000-00A-018A-D_014-00_EN-US.xml

to

CIWS15-AAAA-A00-00-0000-00A-018A-D.xml

which removes DMC- and _014-00_EN-US from the end.

I need to add this to a code that will fix a directory of files.

Upvotes: 1

Views: 166

Answers (2)

Matthias
Matthias

Reputation: 4010

This problem (if I understand it correctly) has a clear separation. Remove extension, remove X characters from beginning and end, and then add the extension again to get the final answer.

import os

oldFileName = 'xxxx-filename-xxxxx.XML'
# remove n chars in beginning, m chars at end
n = 5
m = 6
name, ext = os.path.splitext(oldFileName)
# splice away the chars, and add the extension
newFileName = '{}{}'.format(name[0:-m][n:], ext)
# newFileName == 'filename.XML'

So in your case, you would use n=4 and m=13.

If you didn't know the length, but you knew you wanted everything up to and including the first dash out, and likewise everything after the first underscore (which would mean there couldn't be underscores in the normal filename or the first part of it), this would work also:

import os

oldFileName = 'DMC-CIWS15-AAAA-A00-00-0000-00A-018A-D_014-00_EN-US.xml'
name, ext = os.path.splitext(oldFileName)
newFileName = '{}{}'.format(name[name.index('-')+1:name.index('_')], ext)
# newFileName == 'CIWS15-AAAA-A00-00-0000-00A-018A-D.xml'

And even if the pattern is something else, but there is a pattern, you can code to match it, like I have here.

Upvotes: 1

Yon P
Yon P

Reputation: 206

Its not nice but I hope this works for you tho

If you know the files that you want to rename all have the same length, you can try:

>>>file = 'DMC-CIWS15-AAAA-A00-00-0000-00A-018A-D_014-00_EN-US.xml'
>>>ext = file[51:]
>>>newFile = file[4:38]+ext

when you print the newFile you now have:

>>>print(newFile)
CIWS15-AAAA-A00-00-0000-00A-018A-D.xml

Upvotes: 0

Related Questions