[英]Shutil.move inside a recursive function
I wrote this function to achieve a similar behavior as in Windows when moving files and directories.我写这个 function 是为了在移动文件和目录时实现与 Windows 类似的行为。 In particular, objects should be overwritten.
特别是,对象应该被覆盖。
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
I took a recursive approach to moving nested source directories like this one我采用了一种递归的方法来移动嵌套的源目录,就像这样
.../source/
dir_A/
dir_B/
file_X
to destination到目的地
.../dest/
dir_A/
dir_B/
file_X
file_Y
On production I get a PermissionError now and then which looks like this:在生产中,我时不时会收到一个 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)
All files were moved but the empty source folder remained.所有文件都已移动,但保留了空的源文件夹。 I can't reproduce this error locally.
我无法在本地重现此错误。 So I my first guess was that this is a server issue.
所以我的第一个猜测是这是一个服务器问题。 Still, I wonder if the nested approach could cause this error.
不过,我想知道嵌套方法是否会导致此错误。
So I guess my question is whether an catched shutil.move error can block another shutil.move operation of a file inside the source directory.所以我想我的问题是捕获的 shutil.move 错误是否可以阻止源目录中文件的另一个 shutil.move 操作。
The problem will probably be in the timing of files deletion and directory deletion.问题可能出在文件删除和目录删除的时间上。 I would try to cancel the immediate deletion of directories and I would delete the directories only at the end.
我会尝试取消立即删除目录,我只会在最后删除目录。
Remove the command line:删除命令行:
os.rmdir(source)
and when the file transfer is complete, then call the command当文件传输完成后,调用命令
shutil.rmtree(source)
Good luck.祝你好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.