Python的os和os.path库提供了许多函数来处理文件路径
导入os和os.path库:import os获取当前工作目录:current_directory = os.getcwd()print("当前工作目录:", current_directory)创建一个新的目录:new_directory = "new_folder"os.mkdir(new_directory) # 这将在当前工作目录下创建一个名为"new_folder"的新目录检查路径是否存在:file_path = "example.txt"if os.path.exists(file_path): print("文件或目录存在")else: print("文件或目录不存在")获取文件或目录的名称:file_name = os.path.basename(file_path)print("文件名:", file_name)获取文件或目录的上级目录:parent_directory = os.path.dirname(file_path)print("上级目录:", parent_directory)连接两个或多个路径组件:combined_path = os.path.join("folder1", "folder2", "file.txt")print("组合后的路径:", combined_path)获取文件的大小:file_size = os.path.getsize(file_path)print("文件大小:", file_size, "字节")重命名文件或目录:os.rename("old_name.txt", "new_name.txt")删除文件或目录:os.remove("file_to_delete.txt") # 删除文件os.rmdir("directory_to_delete") # 删除目录,注意:目录必须为空才能删除以上只是os和os.path库中一些常用的函数,更多函数可以参考官方文档:
os: https://docs.python.org/zh-cn/3/library/os.htmlos.path: https://docs.python.org/zh-cn/3/library/os.path.html

