[TOC]
the
- Necessary preparations
>>> import os
1. os.getcwd()
- Get the current path
>>> os.getcwd()
'C:\\Users\\York'
2. os.chdir()
Change the path
The following routes are available
- Absolute path
- relative path
\\
/
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 ()
- Listed path
>>> os.listdir()
['Assembly', 'C', 'C++', 'Java', 'Python3', 'Ruby']
4. os.makedir ()
- Create a folder
>>> 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. Value
Show | DEFINITIONS |
---|---|
os.curdir | The value of the current directory |
os.pardir | Parent directory value |
os.sep | Current system path delimiter |
os.linesep | The current system of newline |
os.name | The current system name |
- Below for the Windows results
>>> os.curdir
'.'
>>> os.pardir
'..'
>>> os.sep
'\\'
>>> os.linesep
'\r\n'
>>> os.name
'nt'
- Below is a Unix- results
>>> os.curdir
'.'
>>> os.pardir
'..'
>>> os.sep
'/'
>>> os.linesep
'\n'
>>> os.name
'posix'
8. os.path
- The necessary import
>>> from os import path as osp
8.1 os.path.abspath()
- Absolute path in the return path
>>> osp.abspath('.')
'd:\\tmp'
8.2 os.path.basename()
- Get the file name part of the path
- Returns the file name string
>>> 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()
- A plurality of route paths together such
- After the new path returns the combined string
>>> bd = r"d:\tmp"
>>> fn = "text.py"
>>> osp.join(bd, fn)
'd:\\tmp\\text.py'
8.4 os.path.split()
- The path cut into the directory and the current file
>>> osp.split(r"d:\tmp\text.py")
('d:\\tmp', 'text.py')
8.5 os.path.isdir ()
- Check whether the directory
>>> osp.isdir(r"d:\tmp")
True
8.6 os.path.exists()
- Check the directory or file if there is
>>> osp.exists(r"d:\tmp")
True
>>> osp.exists(r"d:\tmp\text.txt")
True
>>> osp.exists(r"d:\tmp\text.py")
False