[Python]OS模块应用

OS提供许多和操作系统交互的功能,允许访问文件,目录,进程,环境变量等。

  • 导入模块,import os

  • 获取当前工作目录,os.getcwd()

current_dir=os.getcwd()
print("当前工作目录:",current_dir)

>>>   当前工作目录: C:\Users\wuyucun
  • 创建目录,os.mkdir()
    • 会把文件夹建立在当前.py文件的所在文件夹的同一层级中。
current_dir=os.getcwd()
new_dir=os.path.join(os.getcwd(),"my_directory")
os.mkdir(new_dir)
  • 遍历目录,os.listdir
files=os.listdir(os.getcwd())
for file in files:
    print(file)

  • 删除文件或者目录,使用os.remove()删除文件,os.rmdir()删除目录
file_to_delete=os.path.join(os.getcwd(),"file_to_delete.txt")
os.remove(file_to_delete)

dir_to_delete=os.path.join(os.getcwd(),"dir_to_delete")
os.rmdir(dir_to_delete)
  • 执行系统命令,使用os.system()
os.system("calc")
  • 获取环境变量,使用os.environ
print(os.environ)
  • 路径操作,使用os.path
    • 文件名获取os.path.basename()
    • 目录名获取os.path.dirname()
    • 文件拓展名获取os.path.splitext()[1]
path="/path/to/file/file.txt"
print("文件名:",os.path.basename(path))

>>>文件名: file.txt 
path="/path/to/file/file.txt"
print("目录名:",os.path.dirname(path))

>>>目录名: /path/to/file
path="/path/to/file/file.txt"
print("文件拓展名:",os.path.splitext(path)[1])

>>>文件拓展名: .txt
  • 计算绝对路径,相对路径,使用os.path.join();os.path.relpath()
txt_path="/path/to/file/file.txt"
pic_path="/path/to/file/pic/file/my_pic.png"
pic_path_abs=os.path.dirname(pic_path)
print("绝对路径:",pic_path)
pic_path_rel=os.path.relpath(pic_path_abs,os.path.dirname(txt_path))
print("相对路径:",pic_path_rel)
pic_path_rel_withname=os.path.join(pic_path_rel,os.path.basename(pic_path))
print("相对路径带文件名:",pic_path_rel_withname)

>>>绝对路径: /path/to/file/pic/file/my_pic.png
>>>相对路径: pic\file
>>>相对路径带文件名: pic\file\my_pic.png
  • 使用os.path.exists()判断路径指向位置是否存在

  • 使用os.path.isabs()判断路径是否是绝对路径

  • 使用os.path.isfile()或者os.path.isdir()判读是否是文件或者路径

  • 使用os.rename(src,dst)重命名文件或者路径

  • 使用os.name获得程序当前的运行环境(这是个属性),目前有posix,nt,java

  • 拓展

    • ./在相对路径中表示当前目录,比如同一文件夹下有两个文件1.html和2.html。用<a href="./2.html">跳转到2.html</a>
    • ../代表上一级文件夹
    • ../../代表上上级文件夹,以此类推
    • ./下一级文件夹/.1html下一级目录。
posted @ 2024-04-17 12:11  不愿透露姓名的小村村  阅读(30)  评论(0)    收藏  举报