>>> import os # 下面的例子就不重复这个导入操作了
>>>
os.getcwd()
>>> os.getcwd()
'C:\Users\York'
>>>
os.chdir()
>>> os.chdir("d:")
>>> os.getcwd()
'D:\'
>>>
>>> os.chdir("d:\tmp\Python3")
>>> os.getcwd()
'd:\tmp\Python3'
>>>
>>> os.chdir("..")
>>> os.getcwd()
'd:\tmp'
>>>
os.listdir()
>>> os.listdir()
['Assembly', 'C', 'C++', 'Java', 'Python3', 'Ruby']
>>>
os.makedir()
>>> os.makedirs("swift")
>>> os.listdir()
['Assembly', 'C', 'C++', 'Java', 'Python3', 'Ruby', 'swift']
>>>
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']
>>>
os.getenv()
>>> os.getenv("PATH")
... (内容较长,略去)
>>>
值
表示 |
释义 |
os.curdir |
当前目录值 |
os.pardir |
父级目录值 |
os.sep |
当前系统的路径分隔符 |
os.linesep |
当前系统的换行符 |
os.name |
当前系统名称 |
Windows 的结果
>>> os.curdir
'.'
>>> os.pardir
'..'
>>> os.sep
'\'
>>> os.linesep
'
'
>>> os.name
'nt'
>>>
类 Unix 的结果
>>> os.curdir
'.'
>>> os.pardir
'..'
>>> os.sep
'/'
>>> os.linesep
'
'
>>> os.name
'posix'
>>>
导入 os.path
>>> from os import path as osp # 下面的例子就不重复这个导入操作了
>>>
os.path.abspath()
>>> osp.abspath('.')
'd:\tmp'
>>>
os.path.basename()
>>> os.system("type nul > text.txt")
0
>>> osp.basename(r"d: mp")
'tmp'
>>> osp.basename(r"d: mp ext.py") # 文件可以不存在
'text.py'
>>>
os.path.join()
- 将多个路径拼合成一个路径
- 返回组合之后的新路径字符串
>>> bd = r"d: mp"
>>> fn = "text.py"
>>> osp.join(bd, fn)
'd:\tmp\text.py'
>>>
os.path.split()
>>> osp.split(r"d: mp ext.py")
('d:\tmp', 'text.py')
>>>
os.path.isdir()
>>> osp.isdir(r"d: mp")
True
>>>
os.path.exists()
>>> osp.exists(r"d: mp")
True
>>> osp.exists(r"d: mp ext.txt")
True
>>> osp.exists(r"d: mp ext.py")
False
>>>