用 makedirs做
时间: 2024-10-17 12:04:51 浏览: 9
用python抓取网页的图片
`makedirs`是Python的os模块提供的另一个用于创建多级目录的方法,相较于`mkdir`,它可以一次性创建包含父目录的所有层级。如果中间的某个目录不存在,它会自动创建。如果你想要使用`makedirs`来完成之前提到的任务,你可以这样做:
```python
import os
student_id = "199"
target_directory = "/usr/" + student_id
try:
os.makedirs(target_directory, exist_ok=True)
print(f"Directory {target_directory} created successfully.")
except Exception as e:
print(f"Failed to create the directory due to error: {str(e)}")
# 查看目标目录是否存在并列出其内容
if os.path.exists(target_directory):
files = os.listdir(target_directory)
if files:
print(f"Files and directories in {target_directory}:")
for file in files:
print(file)
else:
print(f"{target_directory} is empty.")
else:
print(f"{target_directory} does not exist or you don't have permission to access it.")
阅读全文