使用上述路径后找不到 Errno2 文件 and/or 我忽略的可能错误

Errno2 file not found after working with said path and/or possible bugs i'm overlooking

我必须创建一个应用程序,它从用户那里获取路径并在单元格内容之后重命名整个文档(在本例中为 excel 个文档)。例如,如果在指定的单元格中,有“2”,则文档将命名为2.xlsx,依此类推,直到所有文件都正确重命名。

问题是,在验证指定路径中有文件后,python退出并[Errno2]没有那个文件或目录。我修改了代码以添加 for files in os.listdir(pathlib.Path(SPEC_PATH).resolve()):,这显然解决了错误问题,但无法识别某些组件(下面的回溯)。

我试过调试它,但对我来说它似乎很好。可能是什么问题?有没有我需要先处理的错误?

代码:

import os
import pandas as pd
import pathlib
import re
from openpyxl import Workbook, load_workbook

# global variables
SPEC_PATH = input("path: ")


def format_date(extracted_string):
    new_s = re.sub(r"[^a-zA-Z0-9 ]", "", extracted_string)
    return new_s


def extract_date(workbook_name):
    for files in os.listdir(pathlib.Path(SPEC_PATH).resolve()):
        if files.endswith(".xlsx") or files.endswith(".xls"):
            new_path = os.path.join(SPEC_PATH, files)
            wb = load_workbook(new_path)
            ws = wb.active
            return ws['C5'].value


# main function
SPEC_PATH = pathlib.Path(SPEC_PATH).resolve()  # will access the given path
count = 0
user_choice = input(
    "Would you like the new name to contain a string before the date?(y/n) ").lower()

while True:
    if user_choice.isalpha():
        if user_choice == 'y':
            head_string = input("Please enter the string: ")
            for x in os.listdir(SPEC_PATH):
                # might include all xl extensions just to be safe
                if x.endswith(".xls") or x.endswith(".xlsx"):
                    extract_date(x)
                    format_date(x)
            for file in os.path.join(SPEC_PATH, file):
                if file.is_file():
                    custom_name = extract_date(file)
                    new_name = f"{head_string}{file.suffix}"
                    if SPEC_PATH.is_file():
                        continue
                    else:
                        try:
                            file.rename(SPEC_PATH/new_name)
                            print("Success!")
                        except OSError as e:
                            print(e)

        else:
            if user_choice == 'n':
                # will count all the files that contain a specified extension
                for files in os.listdir(SPEC_PATH):
                    # might include all xl extensions just to be safe
                    if files.endswith(".xls") or files.endswith(".xlsx"):
                        count += 1
                        extract_date(files)
                        format_date(files)
                        if files.is_file():
                            custom_name = extract_date(files)
                            new_name = f"{files.suffix}"
                            if SPEC_PATH.is_file():
                                continue
                            else:
                                try:
                                    file.rename(SPEC_PATH/new_name)
                                    print("Success!")
                                except OSError as e:
                                    print(e)
    else:
        if user_choice.isnumeric() or user_choice != 'y' or user_choice != 'n':
            print("Please enter a valid choice!")
            break

另外,我现在有这个错误:

  File "e:\renameFiles\smallComponentsTest.py", line 62, in <module>
    if files.is_file():
AttributeError: 'str' object has no attribute 'is_file' ```
 

这解决了所有问题并完成了重命名序列。

import os
import pathlib
                if user_choice == 'y':
                    head_string = input("Please enter the string: ")

                    # renaming operation
                    for x in os.listdir(SPEC_PATH):
                        full_path = os.path.join(SPEC_PATH, x)
                        extension = pathlib.Path(full_path).suffix
                        custom_name = extract_date(full_path)
                        new_name = f"{head_string}{custom_name}{extension}"
                        try:
                            os.rename(os.path.join(SPEC_PATH, x),
                                      os.path.join(SPEC_PATH, new_name))
                            print("Success!")
                            counter += 1
                        except OSError as e:
                            print(e)
                            counter += 1