python1、创建一个名为 projects 的目录; 2、将students_copy.txt 文件重命名为 copy.txt; 3、将文件copy.txt放到projects 的目录里; 4、列举projects 目录里的内容。
时间: 2024-12-01 18:29:40 浏览: 16
在Python中,你可以使用os模块来进行文件和目录的操作。以下是按照你的需求逐个步骤完成:
1. 创建一个名为 "projects" 的目录,可以使用 `os.mkdir` 函数:
```python
import os
if not os.path.exists("projects"):
os.mkdir("projects")
```
2. 将 "students_copy.txt" 重命名为 "copy.txt",你可以先读取原文件内容再写入新的文件:
```python
with open("students_copy.txt", "r") as src_file, open("copy.txt", "w") as dst_file:
content = src_file.read()
dst_file.write(content)
os.rename("students_copy.txt", "copy.txt")
```
注意这里假设 "students_copy.txt" 存在于当前工作目录下。
3. 将 "copy.txt" 放到 "projects" 目录里,你需要使用 `os.path.join` 来获取完整的路径,然后移动文件:
```python
src_path = "copy.txt"
dst_path = os.path.join("projects", "copy.txt")
os.replace(src_path, dst_path)
```
4. 列举 "projects" 目录里的内容,可以使用 `os.listdir`:
```python
project_files = os.listdir("projects")
print(f"projects 目录下的内容: {project_files}")
```
这个操作会返回一个包含目录内所有非目录项的列表。
现在,如果你运行这段代码,你应该会在当前目录下看到 "projects" 目录,并且里面有一个 "copy.txt" 文件。请注意,实际操作前需要确认 "students_copy.txt" 是否存在。
阅读全文
相关推荐















