filenotfounderror和shutil.Error在维护目录结构的同时将特定目录移至新位置时
我拥有以下目录结构:
/home/usr/source
fg-2022-07-07
upload
CP_results_001
file.txt
CP_results_002
file.txt
CP_data_001
file.txt
CP_data_002
file.txt
/home/usr/destination
我想将包含字符串“结果”及其内容的目录移至新目录(/home/home/usr/destinate),以便所需的最终结果如下:
/home/usr/source
fg-2022-07-07
upload
CP_data_001
file.txt
CP_data_002
file.txt
/home/usr/destination
fg-2022-07-07
upload
CP_results_001
file.txt
CP_results_002
file.txt
这是我的代码:这是我的代码:
import os
import shutil
SRC = '/home/usr/source'
DEST = '/home/usr/destination'
for dirpath, dirnames, filenames in os.walk(SRC):
for folders in dirnames:
if "results_" in folders:
print('Directory:', folders, 'will be moved from', dirpath, 'to', DEST)
source_path = os.path.join(dirpath, folders)
print(source_path)
destination_path = source_path.replace(SRC, DEST, 1)
print(destination_path)
shutil.move(source_path, destination_path)
实际结果如下:
/home/usr/source
fg-2022-07-07
upload
CP_results_001
file.txt
CP_results_002
file.txt
CP_data_001
file.txt
CP_data_002
file.txt
/home/usr/destination
fg-2022-07-07
upload
CP_results_002
file.txt
我会得到以下错误类型(不包括具体细节):
os.rename(src, real_dst)
FileNotFoundError: [Errno 2] No such file or directory:
During handling of the above exception, another exception occurred:
shutil.Error:
[Errno 22] Invalid argument:
因此,我将获得部分副本而不是全部移动。
I have the the following directory structures:
/home/usr/source
fg-2022-07-07
upload
CP_results_001
file.txt
CP_results_002
file.txt
CP_data_001
file.txt
CP_data_002
file.txt
/home/usr/destination
I want to move directories containing the string "results_", and their contents, to a new directory (/home/usr/destination) such that the desired final result is as follows:
/home/usr/source
fg-2022-07-07
upload
CP_data_001
file.txt
CP_data_002
file.txt
/home/usr/destination
fg-2022-07-07
upload
CP_results_001
file.txt
CP_results_002
file.txt
Here's my code:
import os
import shutil
SRC = '/home/usr/source'
DEST = '/home/usr/destination'
for dirpath, dirnames, filenames in os.walk(SRC):
for folders in dirnames:
if "results_" in folders:
print('Directory:', folders, 'will be moved from', dirpath, 'to', DEST)
source_path = os.path.join(dirpath, folders)
print(source_path)
destination_path = source_path.replace(SRC, DEST, 1)
print(destination_path)
shutil.move(source_path, destination_path)
The actual result is as follows:
/home/usr/source
fg-2022-07-07
upload
CP_results_001
file.txt
CP_results_002
file.txt
CP_data_001
file.txt
CP_data_002
file.txt
/home/usr/destination
fg-2022-07-07
upload
CP_results_002
file.txt
I get the following error types (excluding specifics):
os.rename(src, real_dst)
FileNotFoundError: [Errno 2] No such file or directory:
During handling of the above exception, another exception occurred:
shutil.Error:
[Errno 22] Invalid argument:
So I am getting a partial copy instead of a full move.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论