python 移动文件夹提示OSError 目录不是空
时间: 2024-09-18 08:08:09 浏览: 60
当你尝试使用Python移动文件夹时,可能会遇到`OSError: [Errno 2] No such file or directory`,这通常是由于源目录(即将被移动的目录)非空导致的。要解决这个问题,你需要在移动之前确保目标目录为空或者处理源目录下的内容。
以下是一个处理此情况的示例:
```python
import os
# 源目录路径
src_dir = '/path/to/source/folder'
# 目标目录路径
dst_dir = '/path/to/destination/folder'
if not os.path.exists(dst_dir):
os.makedirs(dst_dir) # 如果目标不存在则创建
# 使用os.walk遍历并移动源目录下的所有文件
for root, dirs, files in os.walk(src_dir):
for file in files:
if file.endswith('.txt'): # 只移动文本文件
src_file = os.path.join(root, file)
dst_file = os.path.join(dst_dir, file)
try:
os.rename(src_file, dst_file)
except FileNotFoundError:
print(f"File {src_file} does not exist.")
except PermissionError as e:
print(f"Permission error occurred while moving {src_file}: {e}")
except OSError as e:
if "Directory not empty" in str(e): # 处理非空目录错误
print(f"Cannot move {src_file}, the destination directory is not empty.")
else:
raise e # 其他类型的OSError
```
这段代码会递归地遍历源目录,移动所有文本文件(以`.txt`结尾),如果目标目录非空,则会捕获`OSError`异常并打印相应的错误信息。
阅读全文
相关推荐

















