在Python中,你可以使用os
模块来处理文件和目录路径。以下是一些常用的操作:
- 获取当前工作目录:
import os current_directory = os.getcwd() print(current_directory)
- 创建新目录:
import os new_directory = "new_folder" os.mkdir(new_directory) # 如果目录已存在,会抛出FileExistsError异常
- 创建多层级目录:
import os path = "parent/child/subchild" os.makedirs(path, exist_ok=True) # exist_ok=True表示如果父目录不存在也允许创建
- 列出目录内容:
import os directory = "my_directory" files = os.listdir(directory) print(files)
- 检查路径是否存在:
import os path = "my_directory" if os.path.exists(path): print("Path exists") else: print("Path does not exist")
- 获取文件名和扩展名:
import os filename = "example.txt" file_extension = os.path.splitext(filename)[1] print(file_extension) # 输出:.txt
- 拼接路径:
import os base_path = "parent/child" file_name = "example.txt" full_path = os.path.join(base_path, file_name) print(full_path) # 输出:parent/child/example.txt
- 替换文件扩展名:
import os filename = "example.txt" new_extension = ".bak" new_filename = os.path.splitext(filename)[0] + new_extension print(new_filename) # 输出:example.bak
这些只是os
模块中关于路径处理的一些基本操作。你可以根据需要进行更多的操作。