You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

复制油管文件自动分类Python代码后持续报错:'nt.DirEntry'无rstrip属性

解决AttributeError: 'nt.DirEntry' object has no attribute 'rstrip'错误

问题根源

你的错误出在两个地方:

  1. shutil.move接收的是scandir返回的nt.DirEntry对象而非文件路径字符串,该对象没有rstrip方法,触发了属性错误;
  2. Windows路径字符串未做转义处理,\U会被Python解析为Unicode转义符,导致路径无效。

修复步骤

1. 修正路径字符串

给Windows路径加上r前缀(原始字符串),避免转义字符解析错误:

source_dir = r"C:\Users\PC\Downloads"
dest_dir_image = r"C:\Users\PC\Music"

2. 修正move_file函数

传递文件路径字符串(entry.path)给shutil.move,同时结合make_unique处理重名文件,防止覆盖:

def move_file(dest, entry, name):
    unique_name = make_unique(dest, name)
    dest_path = join(dest, unique_name)
    move(entry.path, dest_path)

3. 跳过目录避免误操作

scandir会返回目录和文件,添加判断只处理文件:

def on_modified(self, event):
    with scandir(source_dir) as entries:
        for entry in entries:
            if entry.is_file():
                name = entry.name
                self.check_image_files(entry, name)

完整修复后的代码

from os import scandir, rename
from os.path import splitext, exists, join
from shutil import move
from time import sleep

import logging

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

# ! FILL IN BELOW
source_dir = r"C:\Users\PC\Downloads"
dest_dir_image = r"C:\Users\PC\Music"

# ? supported image types
image_extensions = [".jpg", ".jpeg", ".jpe", ".jif", ".jfif", ".jfi", ".png", ".gif", ".webp", ".tiff", ".tif", ".psd", ".raw", ".arw", ".cr2", ".nrw",
                    ".k25", ".bmp", ".dib", ".heif", ".heic", ".ind", ".indd", ".indt", ".jp2", ".j2k", ".jpf", ".jpf", ".jpx", ".jpm", ".mj2", ".svg", ".svgz", ".ai", ".eps", ".ico"]

def make_unique(dest, name):
    filename, extension = splitext(name)
    counter = 1
    # * IF FILE EXISTS, ADDS NUMBER TO THE END OF THE FILENAME
    while exists(join(dest, name)):
        name = f"{filename}({str(counter)}){extension}"
        counter += 1

    return name


def move_file(dest, entry, name):
    unique_name = make_unique(dest, name)
    dest_path = join(dest, unique_name)
    move(entry.path, dest_path)


class MoverHandler(FileSystemEventHandler):
    def on_modified(self, event):
        with scandir(source_dir) as entries:
            for entry in entries:
                if entry.is_file():
                    name = entry.name
                    self.check_image_files(entry, name)


    def check_image_files(self, entry, name):  # * Checks all Image Files
        for image_extension in image_extensions:
            if name.endswith(image_extension) or name.endswith(image_extension.upper()):
                move_file(dest_dir_image, entry, name)
                logging.info(f"Moved image file: {name}")


# ! NO NEED TO CHANGE BELOW CODE
if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    path = source_dir
    event_handler = MoverHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            sleep(10)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

额外说明

  • 用join拼接路径比字符串格式化更安全,能自动适配不同系统的路径分隔符;
  • 加入entry.is_file()判断后,不会误移动下载文件夹里的子目录。

内容的提问来源于stack exchange,提问作者SohrabFarjami

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 21:48:13