在Python中,您可以使用os
模块来操作路径。以下是一些常见的路径操作方法:
- 获取当前工作目录:
import os current_dir = os.getcwd() print(current_dir)
- 连接路径:
import os path1 = '/path/to/dir' path2 = 'file.txt' full_path = os.path.join(path1, path2) print(full_path)
- 检查路径是否存在:
import os path = '/path/to/dir' if os.path.exists(path): print("Path exists") else: print("Path does not exist")
- 创建目录:
import os new_dir = '/path/to/new/dir' os.mkdir(new_dir)
- 列出目录下的文件和子目录:
import os path = '/path/to/dir' contents = os.listdir(path) for item in contents: print(item)
这些是一些常见的路径操作方法,您可以根据您的需求进一步扩展和使用。