When you use os.walk
and then iterate through the files, remember that you are only iterating through file names - not the full path (which is what is needed by os.rename
in order to function properly). You can adjust by adding the full path to the file itself, which in your case would be represented by joining directname
and filename_zero
together using os.path.join
:
os.rename(os.path.join(directname, filename_zero),
os.path.join(directname, filename_zero.replace(".", "")))
Also, not sure if you use it elsewhere, but you could remove your filename_split
variable and define filename_zero
as filename_zero = os.path.splitext(file)[0]
, which will do the same thing. You may also want to change customer_folders_path = r"C:\Users\All\Documents\Cust"
to customer_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:
import os
customer_folders_path = "C:/Users/All/Documents/Cust"
for directname, directnames, files in os.walk(customer_folders_path):
for f in files:
# Split the file into the filename and the extension, saving
# as separate variables
filename, ext = os.path.splitext(f)
if "." in filename:
# If a '.' is in the name, rename, appending the suffix
# to the new file
new_name = filename.replace(".", "")
os.rename(
os.path.join(directname, f),
os.path.join(directname, new_name + ext))