Python os - zhongjiajie/zhongjiajie.github.com GitHub Wiki

Python-os

os.sep

获取操作系统的路径分隔符: linux/unix为/, windows为\\

os.getcwd

获得当前工作路径,相当于shell的pwd

os.listdir

获取指定路径的文件/文件夹列表,相当于shell的ls,比较常与os.getcwd()混用获取当前路径的文件或文件夹os.listdir(os.getcwd())

os.walk

遍历指定的文件夹,os.walk的运行逻辑是os.listdir指定文件夹,然后返回该文件夹文件夹路径, 文件夹下的所有文件夹,文件夹下的所有文件,如果下存在非空子文件夹,则会继续遍历子文件夹,直到返回的子文件夹为空就停止.

for root, dirs, files in os.walk(PATH):
    # 可以在这里进行一些必要的操作
    # 如过滤文件夹 dirs[:] = [d for d in dirs if d not in exclude]
    # 文件夹排序 dirs.sort()
    print(root, dirs, files)
    print("---> start next walk.")

注意os.walk返回的不是有序的文件/文件夹

  • 如果想要返回简单的有序的文件夹/文件,需要对walk结果进行处理

    for root, dirs, files in os.walk(PATH):
        dirs.sort()
        files.sort()
        print(root, dirs, files)
  • 如果想要比较复杂的排序方式,如本wiki中的_Sidebar.md文件自动生成,可以使用os.listdir进行自定义

    # 例子是这个wiki项目的_Sidebar.md自动生成脚本 要求文件夹/文件排序,先输出文件夹,再输出文件,对文件夹进行深度优先搜索.
    sorted_dir = []
    sorted_file = []
    dir_content = os.listdir(PATH)
    for df in sorted(dir_content):
        full_path = os.path.join(PATH, df)
        # now are sorted but mix with dirs and files
        if os.path.isdir(full_path):
            sorted_dir.append(full_path)
            # if you want to go deep in dir you could do in this
        else:
            sorted_file.append(sorted_file)

os.path

os.path.dirname

获取路径的文件夹路径os.path.dirname(os.path.realpath(__file__))当前文件的文件夹路径

os.path.basename

获取路径的文件夹名称os.path.basename(os.getcwd())获得当前文件路径的文件夹名称.如果是文件路径,则会返回文件名,所以最好使用的时候加判断当前路径是文件夹还是文件

os.path.join

将参数通过os.sep链接起来,合成路径

os.chdir

切换当前工作路径,如果有时候你只需要临时切换路径然后回来的,可以使用上下文管理器切换去目标路径然后回来

from contextlib import contextmanager
import os

@contextmanager
def cd(newdir):
    prevdir = os.getcwd()
    os.chdir(os.path.expanduser(newdir))
    try:
        yield
    finally:
        os.chdir(prevdir)

# 然后就可以这样进行调用了
os.chdir('/home')
with cd('/tmp'):
    # something you do in '/tmp' dir
# Directory is now back to '/home'.

os.unlink

删除文件,如果文件是一个目录则返回一个错误,如果是文件夹应该使用shutil

FAQ

获取父目录名

这里

# python2
# 目录结构的父目录
import os
print os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 运行环境的父目录
print(os.path.dirname(os.getcwd()))

# python3
# 上面的方法适用 外加
print(pathlib.Path().absolute().parent)
print(pathlib.Path(__file__).parent.parent)

⚠️ **GitHub.com Fallback** ⚠️