温馨提示×

如何使用Python的path库进行文件路径操作

小樊
81
2024-08-30 09:54:21
栏目: 编程语言

Python的os和os.path库提供了许多函数来处理文件路径

  1. 导入os和os.path库:
import os
  1. 获取当前工作目录:
current_directory = os.getcwd()
print("当前工作目录:", current_directory)
  1. 创建一个新的目录:
new_directory = "new_folder"
os.mkdir(new_directory)  # 这将在当前工作目录下创建一个名为"new_folder"的新目录
  1. 检查路径是否存在:
file_path = "example.txt"
if os.path.exists(file_path):
    print("文件或目录存在")
else:
    print("文件或目录不存在")
  1. 获取文件或目录的名称:
file_name = os.path.basename(file_path)
print("文件名:", file_name)
  1. 获取文件或目录的上级目录:
parent_directory = os.path.dirname(file_path)
print("上级目录:", parent_directory)
  1. 连接两个或多个路径组件:
combined_path = os.path.join("folder1", "folder2", "file.txt")
print("组合后的路径:", combined_path)
  1. 获取文件的大小:
file_size = os.path.getsize(file_path)
print("文件大小:", file_size, "字节")
  1. 重命名文件或目录:
os.rename("old_name.txt", "new_name.txt")
  1. 删除文件或目录:
os.remove("file_to_delete.txt")  # 删除文件
os.rmdir("directory_to_delete")  # 删除目录,注意:目录必须为空才能删除

以上只是os和os.path库中一些常用的函数,更多函数可以参考官方文档:

  • os: https://docs.python.org/zh-cn/3/library/os.html
  • os.path: https://docs.python.org/zh-cn/3/library/os.path.html

0