1

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(".", ""))
4

2 回答 2

2

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))
于 2013-01-06T05:29:23.913 回答
1

You need to use the original filename as the first parameter to os.rename and handle the case where the filename didn't have a period in the first place. How about:

customer_folders_path = r"C:\Users\All\Documents\Cust"
for directname, directnames, files in os.walk(customer_folders_path):
    for fn in files:
        if '.' in fn:
            fullname = os.path.join(directname, fn)
            os.rename(fullname, os.path.splitext(fullname)[0])
于 2013-01-06T06:53:10.567 回答