Shutil.移动到递归函数内部



我编写这个函数是为了实现在Windows中移动文件和目录时类似的行为。特别是,对象应该被覆盖。

from pathlib import Path
import shutil
import os

def move_anyhow(source: Path | str, dest: Path | str) -> Path:
"""
Move source (directory or file) and overwrite files with same name in dest if exists.
"""
try:
shutil.move(source, dest)
except shutil.Error:
if source.is_file():
shutil.move(source, dest / source.name)
else:
for path in source.iterdir():
move_anyhow(path, dest / source.name)
os.rmdir(source)
return dest / source.name

我采用递归方法移动嵌套的源目录,就像下面这个

.../source/
dir_A/
dir_B/
file_X

目的地

.../dest/
dir_A/
dir_B/
file_X
file_Y

在生产中,我得到一个PermissionError现在,然后看起来像这样:

PermissionError: [Errno 13] Permission denied: '/delivery/post/01_FROM_CF/W22_FW/50479944_003' -> '/delivery/post/01_FROM_CF/ERROR/W22_FW/50479944_003'
File "shutil.py", line 813, in move
os.rename(src, real_dst)
OSError: [Errno 39] Directory not empty: '/delivery/post/01_FROM_CF/W22_FW/50479944_003'
File "ors/path.py", line 34, in move_anyhow
shutil.move(source, dest)
File "shutil.py", line 831, in move
rmtree(src)
File "shutil.py", line 728, in rmtree
onerror(os.rmdir, path, sys.exc_info())
File "shutil.py", line 726, in rmtree
os.rmdir(path)

所有文件被移动,但空的源文件夹保留。我无法在本地重现此错误。所以我的第一个猜测是,这是一个服务器问题。不过,我想知道嵌套的方法是否会导致这个错误。

所以我想我的问题是一个被抓住的水是否。移动错误会阻塞另一个通道。移动源目录下文件的操作。

问题可能出在文件删除和目录删除的时间上。我将尝试取消立即删除目录,并且只在目录末尾删除目录。

删除命令行:

os.rmdir(source)
当文件传输完成后,调用命令
shutil.rmtree(source)

好运。

最新更新