使用Python从多个文件名中删除句点

时间:2013-01-06 05:20:16

标签: python python-2.7

我发现了几个相关的帖子但是当我尝试使用建议的代码时,我不断收到“系统找不到指定的文件”。我想这是一种路径问题。 “Cust”文件夹中有几个文件夹,每个文件夹都有几个文件,有些文件夹有“。”在我需要删除的文件名中。知道我错在哪里吗?

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

2 个答案:

答案 0 :(得分:2)

当您使用os.walk然后遍历文件时,请记住您只是遍历文件名 - 而不是完整路径(这是os.rename为了正常运行所需的路径) 。您可以通过添加文件本身的完整路径进行调整,在您的情况下,可以使用directname加入filename_zeroos.path.join来表示:

os.rename(os.path.join(directname, filename_zero), 
          os.path.join(directname, filename_zero.replace(".", "")))

此外,不确定您是否在其他地方使用它,但您可以删除filename_split变量并将filename_zero定义为filename_zero = os.path.splitext(file)[0],这将执行相同的操作。您可能还希望将customer_folders_path = r"C:\Users\All\Documents\Cust"更改为customer_folders_path = "C:/Users/All/Documents/Cust",因为Python将正确解释该目录。

编辑:正如@bozdoz明智指出的那样,当您拆分后缀时,您将丢失“原始”文件,因此无法找到它。以下是一个适合您情况的示例:

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))

答案 1 :(得分:1)

您需要使用原始文件名作为os.rename的第一个参数,并处理文件名首先没有句点的情况。怎么样:

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])