Переименование файлов XLS с использованием значения ячейки - удаление пробелов и специальных символов - PullRequest
1 голос
/ 13 июля 2020

Ситуация: Я пытаюсь переименовать файлы XLS в каталоге, используя заданное значение ячейки c из каждого файла (т.е. ячейка A4 содержит «Name1», используйте A4 для создания Name1.xls) . Я нашел сценарий, который будет работать для моих целей.

Проблема, которую я пытаюсь решить: Каждая ячейка, которую я пытаюсь использовать, поскольку имя файла содержит пробелы и специальные символы. В идеале я бы хотел удалить все специальные символы и пробелы и использовать их в качестве значения для имени каждого файла. Я не очень знаком с регулярным выражением, поэтому я не уверен, следует ли мне изменять часть кода 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.')

Заранее благодарим за любую помощь, совет, подсказки, которые вы можете дать!

1 Ответ

0 голосов
/ 04 августа 2020

Я думаю, что filename.endswith('.xls.xlsx') не будет работать так, как ожидается, следуя документации str.endswith , вы можете использовать tuple (.endswith(('.xls','.xlsx')).) Для соответствия как .xls, так и .xlsx, кроме того, если вы работаете с обоими типами файлов, лучше знать исходное расширение и сопоставить этот суффикс во время операции переименования, поскольку они интерпретируются по-разному.

... информация [ ...] для форматов XLS и XLSX сильно различаются. XLS основан на BIFF (двоичном формате файла обмена), и поэтому информация напрямую сохраняется в двоичном формате. С другой стороны, XLSX основан на формате Office Open XML, формате файла, который был получен из XML ... [ 1 ]

Вы можете используйте _, extension = os.path.splitext(filename), чтобы получить только часть расширения, которая будет использоваться позже при операции переименования.

Чтобы удалить специальные символы и пробелы, вы можете использовать re.sub("[^a-zA-Z0-9]", "", nameCell). Если строка после : может содержать only специальные символы и пробелы, обязательно проверьте наличие пустой строки перед записью имени файла.

...
...
    # 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:
            ...
    ...
    ...
...