Python: 将文件从文件夹及子文件夹移动到另一个类似目录

2 投票
2 回答
5591 浏览
提问于 2025-04-16 23:54

我有两个源文件的路径:

C:\Same\Path\To\File\unknown\
C:\Same\Path\To\File\unrecognized\

还有一个目标路径:

C:\Same\Path\To\File\Import

这些路径下的子文件夹都是一样的。总共有10到15个文件夹,它们的名字都是三位数的,比如233。

如果这些源路径的子文件夹里有文件,我想把它们从原来的地方剪切(移动)到目标目录,并保持和源路径一样的结构。我对Python还不太熟悉,所以任何帮助都非常感谢。

2 个回答

1

可以看看 shutil 这个模块。

3

我觉得你想要的功能是 shutil.movepy3k 文档):

Help on function move in module shutil:

move(src, dst)
Recursively move a file or directory to another location. This is
similar to the Unix "mv" command.

If the destination is a directory or a symlink to a directory, the source
is moved inside the directory. The destination path must not already
exist.

If the destination already exists but is not a directory, it may be
overwritten depending on os.rename() semantics.

If the destination is on our current filesystem, then rename() is used.
Otherwise, src is copied to the destination and then removed.
A lot more could be done here...  A look at a mv.c shows a lot of
the issues this implementation glosses over.

撰写回答