Reputation: 357
Beginner question: I am trying to rename all .xlsx files within a directory. I understand how to replace a character in string with another, but how about removing? More specifically, I have multiple files in a directory: 0123_TEST_01, 0456_TEST_02. etc. I am trying to remove the prefix in the file name, which would result in the following: TEST_01, TEST_02.
I am attempting to use os.rename and throw it into a loop, but am unsure if I should use len() and some math to try and return the correct naming convention. The below code is where I currently stand. Please let me know if this does not make sense. Thanks.
import os
import shutil
import glob
src_files = os.listdir('C:/Users/acars/Desktop/b')
for file_name in src_files:
os.rename(fileName, filename.replace())
Upvotes: 3
Views: 2351
Reputation: 180502
Just split once on an underscore and use the second element, glob will also find all your xlsx
file for you are return the full path:
from os import path, rename
from glob import glob
src_files = glob('C:/Users/acars/Desktop/b/*.xlsx')
pth = 'C:/Users/acars/Desktop/b/'
for file_name in src_files:
rename(file_name, path.join(pth, path.basename(file_name).split("_",1)[1])
If you only have xlsx files and you did not use glob you would need to join the paths:
from os import path, rename
from glob import glob
pth = 'C:/Users/acars/Desktop/b'
src_files = os.listdir(pth)
for file_name in src_files:
new = file_name.split("_", 1)[1]
file_name = path.join(pth, file_name)
rename(file_name, path.join(pth, new))
Upvotes: 1
Reputation: 12108
Just split the file name by underscore, ignore the first part, and join it back again.
>>> file_name = '0123_TEST_01'
>>> '_'.join(file_name.split('_')[1:])
'TEST_01'
Your code will look like this:
for file_name in src_files:
os.rename(file_name, '_'.join(file_name.split('_')[1:]))
Upvotes: 1