Python 使用单元格值重命名XLS文件-删除空格和特殊字符

Python 使用单元格值重命名XLS文件-删除空格和特殊字符,python,regex,openpyxl,Python,Regex,Openpyxl,情况: 我试图使用每个文件中的特定单元格值重命名目录中的XLS文件(即单元格A4包含“Name1”,使用A4创建Name1.XLS)。我发现了一个脚本,可以满足我的需要 我试图解决的问题: 我试图用作文件名的每个单元格都有空格和特殊字符。理想情况下,我希望删除所有特殊字符和空格,并将其用作命名每个文件的值。我对regex不是很熟悉,所以我不确定是否应该修改fileNameCheck=re.compile(“[^\w\s-]”)代码的一部分,或者如果不是块,则首先修改 见以下代码: # Impor

情况: 我试图使用每个文件中的特定单元格值重命名目录中的XLS文件(即单元格A4包含“Name1”,使用A4创建
Name1.XLS
)。我发现了一个脚本,可以满足我的需要

我试图解决的问题: 我试图用作文件名的每个单元格都有空格和特殊字符。理想情况下,我希望删除所有特殊字符和空格,并将其用作命名每个文件的值。我对regex不是很熟悉,所以我不确定是否应该修改
fileNameCheck=re.compile(“[^\w\s-]”)
代码的一部分,或者如果不是块,则首先修改

见以下代码:

# Import required modules
import openpyxl
import os
import re
import shutil

# File path

filePath = 'C:\\Users\name\Documents\Python\folder'

# Cell containing new file name
cellForFileName = 'A3'

# Check to see if the file path exists
if os.path.exists(filePath):

    # Change the current working directory
    os.chdir(filePath)

    # Check if there are any files in the chosen directory
    if len(os.listdir(filePath)) == 0:

        print('There are no files to rename')

    else:

        # Renamed file count
        filesRenamed = 0

        # Process the files at the path
        for filename in os.listdir(filePath):

            # Check if the file is an Excel file, excluding temp files
            if filename.endswith('.xls.xlsx') and not filename.startswith('~'):

                try:

                    # Open the file and find the first sheet
                    workbook = openpyxl.load_workbook(filename)
                    worksheet = workbook.worksheets[0]

                    # Check if there is a value in the cell for the new file name
                    if worksheet[cellForFileName].value is not None:

                        # Check to see if the cell value is valid for a file name
                        fileNameCheck = re.compile('[^\w,\s-]')
                        if not fileNameCheck.search(worksheet[cellForFileName].value):

                            # Construct the new file name
                            newFileName = worksheet[cellForFileName].value + '.xlsx'

                            # Close the workbook
                            workbook.close()

                            # Rename the file
                            shutil.move(filename, newFileName)

                            # Output confirmation message
                            print('The file "' + filename + '" has been renamed to "'
                                  + newFileName + '".')

                            # Increment the count
                            filesRenamed += 1

                        else:

                            # Display a message saying the file could not be renamed
                            print('The file "' + filename + '" could not be renamed.')

                            # Close the workbook
                            workbook.close()

                    else:

                        # Display a message saying the file could not be renamed
                        print('The file "' + filename + '" could not be renamed.')

                        # Close the workbook
                        workbook.close()

                except PermissionError as e:

                    # Display a message saying the file could not be renamed
                    print('The file "' + filename + '" could not be renamed.')

        # Display a message regarding the number of files renamed
        if filesRenamed == 1:
            print(str(filesRenamed) + ' file has been renamed.')
        else:
            print(str(filesRenamed) + ' files have been renamed.')

else:

    # Display a message stating that the file path does not exist
    print('File path does not exist.')

提前感谢您提供的任何帮助、建议和提示

我认为
文件名.endswith('.xls.xlsx')
不会像预期的那样工作,在文档之后,您可以使用
元组(
.endswith('.xls','.xlsx'))
)来匹配
.xls
.xlsx
,此外,如果使用这两种类型的文件,最好在重命名操作期间知道原始扩展名并匹配后缀,因为它们以不同的方式解释

。。。对于XLS和XLSX格式,存储的信息[…]大不相同。XLS基于BIFF(二进制交换文件格式),因此,信息直接存储为二进制格式。另一方面,XLSX基于Office Open XML格式,这是一种从XML派生的文件格式。。。[]

您可以使用
\扩展名=os.path.splitext(文件名)
仅获取扩展名部分,以便稍后在重命名操作中使用

要删除特殊字符和空格,可以使用
re.sub([^a-zA-Z0-9],“”,nameCell)
。如果
后面的字符串只允许包含
特殊字符和空格,请确保在写入文件名之前测试空字符串

...
...
    # Process the files at the path
    for filename in os.listdir(filePath):
        # get extension to use later on file rename
        _, extension = os.path.splitext(filename)
        if filename.endswith(('.xls','.xlsx')) and not filename.startswith('~'):
            try:
                workbook = openpyxl.load_workbook(filename)
                worksheet = workbook.worksheets[0]
                # get the text after the ":"
                nameCell = re.search(":(.+)", worksheet[cellForFileName].value).group(1)
                # or use str.split(":")[1], make sure the range exists
                workbook.close()

                if nameCell is not None:
                    # remove special characters and spaces
                    clearName = re.sub("[^a-zA-Z0-9]", "", nameCell)
                    newFileName = clearName + extension
                    shutil.move(filename, newFileName)
                    print('The file "' + filename + '" has been renamed to "'
                            + newFileName + '".')
                    filesRenamed += 1
                else:
                    print('The file "' + filename + '" could not be renamed.')

            except PermissionError as e:
            ...
    ...
    ...

我认为
filename.endswith('.xls.xlsx')
不会像预期的那样工作,遵循文档,您可以使用
元组(
.endswith('.xls','.xlsx'))
)来匹配
.xls
.xlsx
,此外,如果使用这两种类型的文件,最好在重命名操作期间知道原始扩展名并匹配后缀,因为它们以不同的方式解释

。。。对于XLS和XLSX格式,存储的信息[…]大不相同。XLS基于BIFF(二进制交换文件格式),因此,信息直接存储为二进制格式。另一方面,XLSX基于Office Open XML格式,这是一种从XML派生的文件格式。。。[]

您可以使用
\扩展名=os.path.splitext(文件名)
仅获取扩展名部分,以便稍后在重命名操作中使用

要删除特殊字符和空格,可以使用
re.sub([^a-zA-Z0-9],“”,nameCell)
。如果
后面的字符串只允许包含
特殊字符和空格,请确保在写入文件名之前测试空字符串

...
...
    # Process the files at the path
    for filename in os.listdir(filePath):
        # get extension to use later on file rename
        _, extension = os.path.splitext(filename)
        if filename.endswith(('.xls','.xlsx')) and not filename.startswith('~'):
            try:
                workbook = openpyxl.load_workbook(filename)
                worksheet = workbook.worksheets[0]
                # get the text after the ":"
                nameCell = re.search(":(.+)", worksheet[cellForFileName].value).group(1)
                # or use str.split(":")[1], make sure the range exists
                workbook.close()

                if nameCell is not None:
                    # remove special characters and spaces
                    clearName = re.sub("[^a-zA-Z0-9]", "", nameCell)
                    newFileName = clearName + extension
                    shutil.move(filename, newFileName)
                    print('The file "' + filename + '" has been renamed to "'
                            + newFileName + '".')
                    filesRenamed += 1
                else:
                    print('The file "' + filename + '" could not be renamed.')

            except PermissionError as e:
            ...
    ...
    ...

如果运行代码会发生什么?具体问题是什么?regex101.com是学习和测试regexes的好网站。嘿,Charlie,如果我有以下名称:Acme Inc.:Acme Sub Inc.,第二个
else
子句运行,导致
“文件xyz无法重命名”
。如果手动删除空格和特殊字符,代码将成功执行。理想情况下,我希望将
字符后的文本作为文件名,但我想我应该从尝试实现第一次迭代开始(删除特殊字符和空格)。将任务分解为多个部分,尤其是查找要重命名的文件。感谢您对解决此问题的指导,非常感谢。我倾向于在
cellforfilename
行中“清理”文件名,拉入数据对象,擦洗它,然后通过代码传递它。这种方法是合理的还是有更好的方法?如果运行代码会发生什么?具体问题是什么?regex101.com是学习和测试regexes的好网站。嘿,Charlie,如果我有以下名称:Acme Inc.:Acme Sub Inc.,第二个
else
子句运行,导致
“文件xyz无法重命名”
。如果手动删除空格和特殊字符,代码将成功执行。理想情况下,我希望将
字符后的文本作为文件名,但我想我应该从尝试实现第一次迭代开始(删除特殊字符和空格)。将任务分解为多个部分,尤其是查找要重命名的文件。感谢您对解决此问题的指导,非常感谢。我倾向于在
cellforfilename
行中“清理”文件名,拉入数据对象,擦洗它,然后通过代码传递它。这种方法是合理的还是有更好的方法?