python模块之os,sys

一、OS

提供对操作系统调用的接口。

 help(os)   #查看os模块帮助文档,里面详细的模块相关函数和使用方法。

官方地址:http://docs.python.org/library/os

帮助文档查阅:

DESCRIPTION
    This exports:
      - all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc.
      - os.path is one of the modules posixpath, or ntpath
      - os.name is 'posix', 'nt', 'os2', 'ce' or 'riscos'
      - os.curdir is a string representing the current directory ('.' or ':')
      - os.pardir is a string representing the parent directory ('..' or '::')
      - os.sep is the (or a most common) pathname separator ('/' or ':' or '\')
      - os.extsep is the extension separator ('.' or '/')
      - os.altsep is the alternate pathname separator (None or '/')
      - os.pathsep is the component separator used in $PATH etc
      - os.linesep is the line separator in text files ('
' or '
' or '
')
      - os.defpath is the default search path for executables
      - os.devnull is the file path of the null device ('/dev/null', etc.)
from os import *

1、获取当前工作目录,即当前python脚本工作的目录路径

  改变工作目录

当前目录为 /flasky

>>> getcwd()
'/flasky'

>>> chdir('/flask/flasky') 
>>> getcwd()               
'/flask/flasky'

2、获取当前目录和父目录

>>> curdir
'.'
>>> pardir
'..'

3、生成多层递归目录(目录下创建目录)

>>> makedirs('flasky/test/test')
>>> system('ls flasky/test/test')
0
>>> 

4、在目录为空时,删除目录,并递归到上一级目录,如若也为空,则删除,依此类推

#删除的目录不为空,则抛出异常
>>> removedirs('test')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/os.py", line 170, in removedirs
    rmdir(name)
OSError: [Errno 39] Directory not empty: 'test'

5、生成/删除单级目录

os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname

6、列出当前文件/目录,以列表形式。(包括隐藏文件)

>>> listdir('.')
['.git', 'app', 'migrations', '.gitignore', 'config.pyc', 'manage.pyc', 'new.py', 'config.py', 'manage.py', 'hello.pyc', 'templates', 'data-dev.sqlite', 'LICENSE', 'requirements.txt', 'yanzhengma.py', 'README.md', 'test', 'tests']

7、文件操作

os.remove()  删除一个文件
os.rename("oldname","newname")  重命名文件/目录
os.stat('path/filename')  获取文件/目录信息

>>> stat('c')
posix.stat_result(st_mode=33188, st_ino=550377, st_dev=2049L, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1500567243, st_mtime=1500567243, st_ctime=1500567292)

8、获取系统的路径符号,操作系统名称

#linux
>>> sep #输出操作系统特定的路径分隔符
'/'
>>> linesep  输出当前平台使用的行终止符
'
'
>>> pathsep  输出用于分割文件路径的字符串
':'
>>> name
'posix'

#windows
>>> sep
'\'
>>> linesep
'
'
>>> pathsep
';'
>>> name
'nt'

9、运行系统命令和查看环境变量

os.system("bash command")  运行shell命令,直接显示
os.environ  获取系统环境变量,以字典形式
ps:环境区分虚拟环境和真实环境,并且远程终端登陆可能会导致不同。

分割线------------------------------------------------------------------------------------------------------------------------------

10、获取文件/目录路径

#返回path规范化的绝对路径
>>> path.abspath('.')
'/flasky'
>>> path.abspath('..')
'/'
>>> path.abspath(curdir)
'/flasky'
>>> path.abspath(curdir)
'/flasky'
>>> path.abspath(pardir)
'/'

#将path分割成目录和文件名二元组返回
>>> path.split('flasky/confin.py')
('flasky', 'confin.py')

 #返回path的目录。其实就是os.path.split(path)的第一个元素
>>> path.dirname('flasky/config.py')
'flasky'
# 返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素
>>> path.basename('flasky/config.py')
'config.py'
>>> path.basename('flasky/')         
''
ps:path.split,path.dirname,path.basename 只直接根据信息返回值,不判断是否真的存在输入的该文件/目录

11、判断文件,目录

#判断路径是否存在,是-True,否-False 返回值
>>> path.exists('/flasky/')
True
>>> path.exists('flasky/') 
False
>>> path.exists('config.py')    
True
ps:若不写绝对路径,也是以当前目录作为基点判断

#判断是否是绝对路径,是-True,否-False 返回值
>>> path.isabs('/flasky')
True
>>> path.isabs('flasky') 
False


#os.path.isfile(path)  如果path是一个存在的文件,返回True。否则返回False
#os.path.isdir(path)  如果path是一个存在的目录,则返回True。否则返回False

12、获取文件/目录修改时间

os.path.getatime(path)  返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path)  返回path所指向的文件或者目录的最后修改时间
 
13、将路径组合
注:第一个绝对路径之前的参数将被忽略??
>>> path.join('/flasky','test','test_c')
'/flasky/test/test_c'
>>> path.join('sas/flasky','test','test_c')
'sas/flasky/test/test_c'
>>> path.join('/sas/flasky','test','test_c')
'/sas/flasky/test/test_c'
#例子
>>> import os
>>> BASE_PATH = os.path.abspath(os.path.dirname(__file__))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined

ps:在shell中直接使用貌似报错,__file__没定义

#放入文件中执行,成功
mport os
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
DATA_PATH =  os.path.join(BASE_PATH,'data')
 
print(BASE_PATH)
print(DATA_PATH)

#/flasky
#/flasky/data

二、SYS

sys.argv           命令行参数List,第一个元素是程序本身路径

sys.exit(n)        退出程序,正常退出时exit(0)
sys.version        获取Python解释程序的版本信息
sys.maxint         最大的Int
sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform       返回操作系统平台名称
sys.stdout.write('please:')
val = sys.stdin.readline()[:-1]

os,sys结合使用返回脚本运行目录

》》》 os.path.realpath(sys.argv[0])
#该方法在将py打包成exe时,路径不会乱。
原文地址:https://www.cnblogs.com/dyzne/p/7235215.html