The os module of python's common modules
The os module provides many functions that allow your program to interact directly with the operating system
1. os.getcwd()
: Get the current working directory, that is, the directory path where the current python script works
In [1]: import os
In [2]: os.getcwd()
Out[2]: '/tmp' # 表示在/tmp目录下运行的
2. os.listdir()
: Returns all files and directory names in the specified directory
In [3]: os.listdir()
Out[3]:
['.XIM-unix',
'.X11-unix',
'.font-unix',
'.Test-unix',
'.ICE-unix',
'replaceContent.py',
'1.log']
3. os.remove()
: The function is used to delete a file
In [6]: os.listdir() # 查看在此工作目录下的所有文件和目录
Out[6]:
['.XIM-unix',
'.X11-unix',
'.font-unix',
'.Test-unix',
'.ICE-unix',
'replaceContent.py',
'1.log']
In [7]: os.remove('1.log') # 删除1.log文件
In [8]: os.listdir()
Out[8]:
['.XIM-unix',
'.X11-unix',
'.font-unix',
'.Test-unix',
'.ICE-unix',
'replaceContent.py']
4. os.removedirs(r"")
: delete multiple directories
In [2]: os.listdir() # 查看当前目录下所有文件和目录名
Out[2]:
['.XIM-unix',
'.X11-unix',
'.font-unix',
'.Test-unix',
'.ICE-unix',
'replaceContent.py',
'aaa']
In [3]: os.removedirs(r"./aaa") # 删除当前目录下aaa目录/文件夹
In [4]: os.listdir()
Out[4]:
['.XIM-unix',
'.X11-unix',
'.font-unix',
'.Test-unix',
'.ICE-unix',
'replaceContent.py']
5. os.path.isfile()
: Determine whether the given path is a file
In [4]: os.listdir() # 查看当前目录下所有文件和目录
Out[4]:
['.XIM-unix',
'.X11-unix',
'.font-unix',
'.Test-unix',
'.ICE-unix',
'replaceContent.py']
In [5]: os.path.isfile("/tmp/replaceContent.py") # 判断这个路径是不是一个文件
Out[5]: True
6. os.path.isdir()
: Determine whether the given path is a directory
In [6]: os.path.isdir("/etc/yum.repos.d") # 判断这个路径是不是目录
Out[6]: True
7. os.path.isabs()
: Determine if it is an absolute path
In [7]: os.path.isabs(".")
Out[7]: False # 不是绝对路径,因为.代表当前目录
In [8]: os.path.isabs("/root/tmp/")
Out[8]: True # 是绝对路径,因为从/root(根)开始
8. os.path.split()
: Returns the directory and filename of a path
In [9]: os.path.split("/root/tmp/replaceContent.py")
Out[9]: ('/root/tmp', 'replaceContent.py') # /root/tmp代表目录,replaceContent.py代表文件名
9. os.path.splitext()
: Separate extension (suffix of file name)
In [10]: os.path.splitext("/root/tmp/replaceContent.py")
Out[10]: ('/root/tmp/replaceContent', '.py') # .py就是文件的后缀名
10. os.path.dirname
: Get the path name
In [12]: os.path.dirname("replaceContent.py")
Out[12]: '' # 空代表当前m路径
In [13]: os.path.dirname("/etc")
Out[13]: '/' # /表示在根下
In [14]: os.path.dirname("/etc/yum.repos.d/")
Out[14]: '/etc/yum.repos.d' #
11. os.path.abspath()
: Get the absolute path
In [15]: os.path.abspath(".") # .代表当前路径
Out[15]: '/tmp' # 返回的结果是绝对路径
12. os.path.basenam()
: Get the file name
In [3]: os.path.basename('1.py')
Out[3]: '1.py' # 没啥卵用
13. os.system()
: run shell command
In [6]: os.system("df -h") # 运行df -h命令
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/centos-root 50G 2.2G 48G 5% /
devtmpfs 3.9G 0 3.9G 0% /dev
tmpfs 3.9G 0 3.9G 0% /dev/shm
tmpfs 3.9G 8.4M 3.9G 1% /run
tmpfs 3.9G 0 3.9G 0% /sys/fs/cgroup
/dev/vda1 509M 175M 335M 35% /boot
tmpfs 783M 0 783M 0% /run/user/0
Out[6]: 0 # 返回结果为0表示运行成功
14. os.getenv('HOME')
: Read the value of the operating system environment variable HOME
In [7]: os.getenv("HOME")
Out[7]: '/root'
15. os.environ
: Returns all environment variables of the operating system
In [10]: os.environ
Out[10]: environ({'XDG_SESSION_ID': '1', 'HOSTNAME': 'host-10-200-137-195', 'TERM': 'xterm', 'SHELL': '/bin/bash', 'HISTSIZE': '1000', 'SSH_CLIENT': '192.168.2.157 55010 22', 'SSH_TTY': '/dev/pts/0', 'QT_GRAPHICSSYSTEM_CHECKED': '1', 'USER': 'root', 'LS_COLORS': 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:', 'MAIL': '/var/spool/mail/root', 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin', 'PWD': '/tmp', 'LANG': 'en_US.UTF-8', 'QT_GRAPHICSSYSTEM': 'native', 'HISTCONTROL': 'ignoredups', 'SHLVL': '1', 'HOME': '/root', 'LOGNAME': 'root', 'SSH_CONNECTION': '192.168.2.157 55010 10.200.137.195 22', 'LESSOPEN': '||/usr/bin/lesspipe.sh %s', 'XDG_RUNTIME_DIR': '/run/user/0', '_': '/usr/local/bin/ipython3', 'OLDPWD': '/opt'})
16. os.environ.setdefault()
: Set system environment variables, only valid when the program is running
In [12]: os.environ.setdefault("JAVA_HOME","/etc") # 仅当前终端有效
Out[12]: '/etc'
# 使用os.environ()可以查看到,但是使用另一个终端就没有这个
17. os.linesep
: Give the line prompt used by the current platform
In [14]: os.linesep
Out[14]: '\n' # Windows使用'\r\n',Linux and MAC使用'\n'
18. os.name()
: Prompt the platform you are using
In [15]: os.name
Out[15]: 'posix' # 对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'
19. os.rename(old_str,new_str)
: Renaming of files
In [16]: os.listdir() # 查看当前目录下所有的文件和目录名
Out[16]:
['.XIM-unix',
'.X11-unix',
'.font-unix',
'.Test-unix',
'.ICE-unix',
'replaceContent.py',
'1.py']
In [17]: os.rename("1.py","test.py") # 把当前目录下的1.py文件重命名为test.py
In [18]: os.listdir()
Out[18]:
['.XIM-unix',
'.X11-unix',
'.font-unix',
'.Test-unix',
'.ICE-unix',
'replaceContent.py',
'test.py']
20. os.makedirs()
: Create a multi-level directory
In [19]: os.makedirs("/root/python/1/2/3/4") # 及时它的上级目录不存在也是可以创建的
21. os.mkdir()
: Create a single directory
In [20]: os.mkdir("python2") # 创建python2目录
In [21]: os.listdir()
Out[21]:
['.XIM-unix',
'.X11-unix',
'.font-unix',
'.Test-unix',
'.ICE-unix',
'replaceContent.py',
'test.py',
'python2']
In [22]: os.path.isdir("python2") # 判断给出的路径是不是目录,当前目录下的python2
Out[22]: True
22. os.stat(file)
: Get a single file attribute
In [23]: os.stat("replaceContent.py")
Out[23]: os.stat_result(st_mode=33188, st_ino=101328662, st_dev=64768, st_nlink=1, st_uid=0, st_gid=0, st_size=1149, st_atime=1525844026, st_mtime=1525744039, st_ctime=1525744039)
其中:
st_mode=33188代表inode 保护模式
st_ino=101328662代表inode 节点号
st_dev=64768代表inode 驻留的设备
st_nlink=1带代表inode 的链接数
st_uid=0代表所有者的用户ID
st_gid=0代表所有者的组ID
st_sizest_size=1149代表普通文件以字节为单位的大小;包含等待某些特殊文件的数据
st_atime=1525844026代表上次访问的时间
st_mtime=1525744039代表最后一次修改的时间
st_ctime=1525744039代表由操作系统报告的"ctime"。在某些系统上(如Unix)是最新的元数据更改的时间,在其它系统上(如Windows)是创建时间(详细信息参见平台的文档)
In [33]: import time
In [34]: time.ctime(1525844026) # time.ctime()把时间戳转换成专门的格式
Out[34]: 'Wed May 9 13:33:46 2018'
23. os.chmod(file,)
: Modify file permissions and timestamps, please see [ http://www.runoob.com/python/os-chmod.html ]
24. os.path.getsize(filename)
: Get file size
In [35]: os.path.getsize('replaceContent.py')
Out[35]: 1149 # 1149个字节
25: os.path.join(dir,filename)
: Combining directory and file names
In [37]: os.path.join("/tmp","test.py")
Out[37]: '/tmp/test.py' # 结合起来
26. os.chdir(dirname)
: Change working directory to dirname
In [38]: os.chdir("/etc") # 更改路径为/etc下
In [39]: os.getcwd() # 得到当前python解释器所在的目录
Out[39]: '/etc'
27. os.get_terminal_size()
: Get the size of the current terminal
In [40]: os.get_terminal_size()
Out[40]: os.terminal_size(columns=137, lines=30) # 30行,每行容纳137个字符
28. os.kill(ID号,signal.SIGKILL)
:kill process