I’ve found several related posts to this but when I try to use the code suggested I keep getting “The system cannot find the file specified”. I imagine it’s some kind of path problem. There are several folders within the “Cust” folder and each of those folders have several files and some have “.” in the file name I need to remove. Any idea what I have wrong here?
customer_folders_path = r"C:\Users\All\Documents\Cust"
for directname, directnames, files in os.walk(customer_folders_path):
for file in files:
filename_split = os.path.splitext(file)
filename_zero = filename_split[0]
if "." in filename_zero:
os.rename(filename_zero, filename_zero.replace(".", ""))
When you use
os.walkand then iterate through the files, remember that you are only iterating through file names – not the full path (which is what is needed byos.renamein order to function properly). You can adjust by adding the full path to the file itself, which in your case would be represented by joiningdirectnameandfilename_zerotogether usingos.path.join:Also, not sure if you use it elsewhere, but you could remove your
filename_splitvariable and definefilename_zeroasfilename_zero = os.path.splitext(file)[0], which will do the same thing. You may also want to changecustomer_folders_path = r"C:\Users\All\Documents\Cust"tocustomer_folders_path = "C:/Users/All/Documents/Cust", as the directory will be properly interpreted by Python.EDIT: As intelligently pointed out by @bozdoz, when you split off the suffix, you lose the ‘original’ file and therefore it can’t be found. Here is an example that should work in your situation: