2

I want to remove a file's last characters that it's name is somedigits plus .py and plus .BR like 0001.py.BR or 0005.py.BR and remove the .BR from the string.

I tried this code

import os
x = input("")
os.rename(x, x[7])

but it sometimes don't work for some file that their names are larger like 00001.py.BR it renames it to 00001.p so is there a way that I just do like this x - ".BR".

1
  • will this work for you ? os.rename(x, x[:-3]) Commented Aug 22, 2019 at 7:21

3 Answers 3

1

if you talking about file path,

then use os.path.splitext()

>>> import os
>>> os.path.splitext('00001.py.BR')[0]
'00001.py'
>>> 
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the built-in split function like this:

import os
x=input("")
x_new = x.split(".BR")[0]
os.rename(x, x_new)

Comments

1

If you're using Python 3, check the standard pathlib:

from pathlib import Path

old_path = Path(input(""))
if old_path.suffix == '.BR':
    old_path.rename(old_path.stem)
else:
    print('this is not a .BR file')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.