[Python3] 030 常用模块 os

[TOC]

os

  • 必要的准备
>>> import os

1. os.getcwd()

  • 获取当前路径
>>> os.getcwd()
'C:\\Users\\York'

2. os.chdir()

  • 改变路径

  • 以下几种路径均可

    • 绝对路径
    • 相对路径
    • \\
    • /
    • r"path"
>>> os.chdir("d:")
>>> os.getcwd()
'D:\\'
>>> 
>>> os.chdir("d:\\tmp\\Python3")
>>> os.getcwd()
'd:\\tmp\\Python3'
>>> 
>>> os.chdir("..")
>>> os.getcwd()
'd:\\tmp'
>>> 

3. os.listdir()

  • 列举路径
>>> os.listdir()
['Assembly', 'C', 'C++', 'Java', 'Python3', 'Ruby']

4. os.makedir()

  • 创建文件夹
>>> os.makedirs("swift")
>>> os.listdir()
['Assembly', 'C', 'C++', 'Java', 'Python3', 'Ruby', 'swift']

5. os.system()

>>> os.system("ls")
'ls' 不是内部或外部命令,也不是可运行的程序
或批处理文件。
1
>>> os.system("dir")
...(内容较长,略去)
0
>>> 
>>> os.system("mkdir Lisp")
0
>>> os.listdir()
['Assembly', 'C', 'C++', 'Java', 'Lisp', 'Python3', 'Ruby', 'swift']

6. os.getenv()

>>> os.getenv("PATH")
... (内容较长,略去)

7. 值

表示 释义
os.curdir 当前目录值
os.pardir 父级目录值
os.sep 当前系统的路径分隔符
os.linesep 当前系统的换行符
os.name 当前系统名称
  • 下方为 Windows 的结果
>>> os.curdir
'.'
>>> os.pardir
'..'
>>> os.sep
'\\'
>>> os.linesep
'\r\n'
>>> os.name
'nt'
  • 下方为 类 Unix 的结果
>>> os.curdir
'.'
>>> os.pardir
'..'
>>> os.sep
'/'
>>> os.linesep
'\n'
>>> os.name
'posix'

8. os.path

  • 必要的导入
>>> from os import path as osp

8.1 os.path.abspath()

  • 返回路径的绝对路径形式
>>> osp.abspath('.')
'd:\\tmp'

8.2 os.path.basename()

  • 获取路径中的文件名部分
  • 返回文件名字符串
>>> os.system("type nul > text.txt")
0
>>> osp.basename(r"d:\tmp")
'tmp'
>>> osp.basename(r"d:\tmp\text.py")  # 文件可以不存在
'text.py'

8.3 os.path.join()

  • 将多个路径拼合成一个路径
  • 返回组合之后的新路径字符串
>>> bd = r"d:\tmp"
>>> fn = "text.py"
>>> osp.join(bd, fn)
'd:\\tmp\\text.py'

8.4 os.path.split()

  • 将路径切割成目录当前文件
>>> osp.split(r"d:\tmp\text.py")
('d:\\tmp', 'text.py')

8.5 os.path.isdir()

  • 检查是否是目录
>>> osp.isdir(r"d:\tmp")
True

8.6 os.path.exists()

  • 检查目录文件是否存在
>>> osp.exists(r"d:\tmp")
True
>>> osp.exists(r"d:\tmp\text.txt")
True
>>> osp.exists(r"d:\tmp\text.py")
False

猜你喜欢

转载自www.cnblogs.com/yorkyu/p/12040702.html