在Python中,可以使用os
和os.path
模块来处理和转换路径。以下是一些常用的方法:
- 获取当前工作目录:
import os current_directory = os.getcwd() print(current_directory)
- 将相对路径转换为绝对路径:
import os relative_path = "example.txt" absolute_path = os.path.abspath(relative_path) print(absolute_path)
- 将绝对路径转换为相对路径:
import os absolute_path = "/home/user/documents/example.txt" relative_path = os.path.relpath(absolute_path) print(relative_path)
- 获取路径中的文件名和目录名:
import os path = "/home/user/documents/example.txt" filename = os.path.basename(path) directory = os.path.dirname(path) print(filename) print(directory)
- 检查路径是否存在:
import os path = "/home/user/documents/example.txt" if os.path.exists(path): print("Path exists") else: print("Path does not exist")
- 创建一个新目录:
import os directory = "new_directory" if not os.path.exists(directory): os.makedirs(directory)
- 遍历目录中的所有文件和子目录:
import os path = "/home/user/documents" for root, dirs, files in os.walk(path): for directory in dirs: print(os.path.join(root, directory)) for file in files: print(os.path.join(root, file))
这些方法可以帮助你在Python中处理和转换路径。根据实际需求,你可以选择合适的方法来实现路径操作。