Python-OS模块学习笔记

 

os(操作系统),操作系统相关功能,可执行一些文件和目录的操作,比如:显示目录下所有文件/删除、新建某个文件/获取文件信息。。。。。。。,且不受平台限制。

## os.name #显示当前使用的平台

>>> os.name
'nt'        *#表示windows平台*
>>>os.name
'posix'   *#表示linux平台*

## os.getcwd() #显示当前python脚本工作路径

>>>os.getcwd()
'C:\\usr\Capital-D\\PycharmProjects\\untitled'   
>>>os.getcwd()
'/root'

## os.listdir('dirname')  #返回指定目录下的所有文件和目录名


>>> os.listdir(os.getcwd())
['.idlerc', '.local', '.PyCharm2019.3', '3D Objects', 'AppData', 'Application Data', 'Contacts', 'Cookies', 'Desktop', 'Documents', 'Downloads', 'Favorites', 'get-pip.py', 'IntelGraphicsProfiles', 'Links', 'Local Settings', 'MicrosoftEdgeBackups', 'Music', 'My Documents', 'NetHood', 'NTUSER.DAT', 'ntuser.dat.LOG1', 'ntuser.dat.LOG2', 'NTUSER.DAT{fd9a35db-49fe-11e9-aa2c-248a07783950}.TM.blf', 'NTUSER.DAT{fd9a35db-49fe-11e9-aa2c-248a07783950}.TMContainer00000000000000000001.regtrans-ms', 'NTUSER.DAT{fd9a35db-49fe-11e9-aa2c-248a07783950}.TMContainer00000000000000000002.regtrans-ms', 'ntuser.ini', 'OneDrive', 'Pictures', 'PrintHood', 'Recent', 'Saved Games', 'Searches', 'SendTo', 'Templates', 'Videos', '\xa1\xb8\xbf\xaa\xca\xbc\xa1\xb9\xb2\xcb\xb5\xa5', '\xd6\xd0\xd2\xf8\xb8\xbb\xb5\xc7\xbd\xc5\xb1\xbe\xc5\xe0\xd1\xb5.mp4']

>>> os.listdir("/root")
['.bash_logout', '.bash_profile', '.bashrc', '.cshrc', '.tcshrc', 'anaconda-ks.cfg', '.bash_history', '.pki', '.ansible', '.lesshst', '.cache', 'a.txt', 'a.ini', 'a.xtx', '.viminfo', '.Xauthority']

## os.remove('filename') #删除一个文件


>>> os.remove('a.xtx')
>>> os.listdir("/root")

['.bash_logout', '.bash_profile', '.bashrc', '.cshrc', '.tcshrc', 'anaconda-ks.cfg', '.bash_history', '.pki', '.ansible', '.lesshst', '.cache', 'a.txt', 'a.ini', '.viminfo', '.Xauthority']


>>> os.remove('/root/a.txt')
>>> os.listdir("/root")

['.bash_logout', '.bash_profile', '.bashrc', '.cshrc', '.tcshrc', 'anaconda-ks.cfg', '.bash_history', '.pki', '.ansible', '.lesshst', '.cache', 'a.ini', '.viminfo', '.Xauthority']

## os.makedirs('dirname/dirname')  #可生成多层递归目录

[root@localhost ~]# ls
a.ini  anaconda-ks.cfg
>>> import os
>>> os.makedirs('/root/aa')
>>> os.makedirs('bb')
>>> os.listdir(os.getcwd())

['.bash_logout', '.bash_profile', '.bashrc', '.cshrc', '.tcshrc', 'anaconda-ks.cfg', '.bash_history', '.pki', '.ansible', '.lesshst', '.cache', 'a.ini', '.viminfo', '.Xauthority', 'aa', 'bb']
>>> os.remove('aa')    #目录无法使用remove删除
Traceback (most recent call last):
  File "", line 1, in
OSError: [Errno 21] Is a directory: 'aa'

## os.rmdir('dirname/dirname')  #删除单个目录

>>> os.makedirs('aa/bb/cc')
>>> os.rmdir('aa/bb/cc')
>>> os.listdir(os.getcwd())

['.bash_logout', '.bash_profile', '.bashrc', '.cshrc', '.tcshrc', 'anaconda-ks.cfg', '.bash_history', '.pki', '.ansible', '.lesshst', '.cache', 'a.ini', '.viminfo', '.Xauthority', 'aa']
>>> exit()
[root@localhost ~]# ls aa/bb/
[root@localhost ~]#

## os.rename("oldname" "newname")  #重命名文件或文件夹

>>> os.getcwd()
'/root'
>>> os.listdir(os.getcwd())
['.bash_logout', '.bash_profile', '.bashrc', '.cshrc', '.tcshrc', 'anaconda-ks.cfg', '.bash_history', '.pki', '.ansible', '.lesshst', '.cache', 'a.ini', '.viminfo', '.Xauthority', 'aa']
>>> os.rename("aa","bb")
>>> os.listdir(os.getcwd())

['.bash_logout', '.bash_profile', '.bashrc', '.cshrc', '.tcshrc', 'anaconda-ks.cfg', '.bash_history', '.pki', '.ansible', '.lesshst', '.cache', 'a.ini', '.viminfo', '.Xauthority', 'bb']
>>> os.rename("a.ini","b.ini")
>>> exit()
[root@localhost ~]# ls
anaconda-ks.cfg  bb  b.ini

## os.system() #运行shell命令,注意这里是打开一个新的shell命令,运行命令,命令结束后关闭shell,返回shell输出值,shell运行成功返回0

>>> os.system("cd /tmp;ls")
ks-script-OZghtd
systemd-private-494491f11d6c421fb8957b3511eb0e26-chronyd.service-CKJmZa
systemd-private-494491f11d6c421fb8957b3511eb0e26-vgauthd.service-L1Gkun
systemd-private-494491f11d6c421fb8957b3511eb0e26-vmtoolsd.service-1iDUOb
yum.log
yum_save_tx.2020-06-08.16-21.qwGauM.yumtx
0
>>> os.system("cd /tmp;")
0
>>> os.system("cd  /dafasfasf")
sh: 第 0 行: cd: /dafasfasf: 没有那个文件或目录
256
 

##os.sep #显示当前平台下路径分割符

>>> os.sep
'/'               #linux

>>> os.sep
'\\'             #windows

##os.environ #获取系统环境变量

>>> os.environ   #linux
{'LESSOPEN': '||/usr/bin/lesspipe.sh %s', 'SSH_CLIENT': '192.168.1.2 54553 22', 'LOGNAME': 'root', 'USER': 'root', 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin', 'HOME': '/root', 'GUESTFISH_RESTORE': '\\e[0m', 'GUESTFISH_INIT': '\\e[1;34m', 'LANG': 'zh_CN.UTF-8', 'TERM': 'xterm', 'SHELL': '/bin/bash', 'SHLVL': '1', 'HISTSIZE': '1000', 'XDG_RUNTIME_DIR': '/run/user/0', 'GUESTFISH_PS1': '\\[\\e[1;32m\\]>\\[\\e[0;31m\\] ', 'XDG_SESSION_ID': '5', '_': '/usr/bin/python', 'SSH_CONNECTION': '192.168.1.2 54553 192.168.1.233 22', 'DISPLAY': 'localhost:11.0', 'GUESTFISH_OUTPUT': '\\e[0m', 'SSH_TTY': '/dev/pts/1', 'HOSTNAME': 'localhost.localdomain', 'HISTCONTROL': 'ignoredups', 'PWD': '/root', 'MAIL': '/var/spool/mail/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:'}
 

>>> os.environ    #windows
{'TMP': 'C:\\Users\\47576\\AppData\\Local\\Temp', 'ONEDRIVECONSUMER': 'C:\\Users\\47576\\OneDrive', 'COMPUTERNAME': 'DESKTOP-MS3T7D2', 'USERDOMAIN': 'DESKTOP-MS3T7D2', 'PSMODULEPATH': 'C:\\Program Files\\WindowsPowerShell\\Modules;C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules', 'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files', 'PROCESSOR_IDENTIFIER': 'Intel64 Family 6 Model 60 Stepping 3, GenuineIntel', 'PROGRAMFILES': 'C:\\Program Files', 'PROCESSOR_REVISION': '3c03', 'SYSTEMROOT': 'C:\\Windows', 'PATH': 'C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Windows\\System32\\OpenSSH\\;C:\\Python27;C:\\Python27\\Scripts;C:\\Users\\47576\\AppData\\Local\\Microsoft\\WindowsApps;', 'PROGRAMFILES(X86)': 'C:\\Program Files (x86)', 'COMSPEC': 'C:\\Windows\\system32\\cmd.exe', 'DRIVERDATA': 'C:\\Windows\\System32\\Drivers\\DriverData', 'TEMP': 'C:\\Users\\47576\\AppData\\Local\\Temp', 'COMMONPROGRAMFILES(X86)': 'C:\\Program Files (x86)\\Common Files', 'PROCESSOR_ARCHITECTURE': 'AMD64', 'ALLUSERSPROFILE': 'C:\\ProgramData', 'LOCALAPPDATA': 'C:\\Users\\47576\\AppData\\Local', 'FPS_BROWSER_USER_PROFILE_STRING': 'Default', 'HOMEPATH': '\\Users\\47576', 'USERDOMAIN_ROAMINGPROFILE': 'DESKTOP-MS3T7D2', 'PROGRAMW6432': 'C:\\Program Files', 'USERNAME': '47576', 'LOGONSERVER': '\\\\DESKTOP-MS3T7D2', 'PROMPT': '$P$G', 'SESSIONNAME': 'Console', 'PROGRAMDATA': 'C:\\ProgramData', 'ONEDRIVE': 'C:\\Users\\47576\\OneDrive', 'FPS_BROWSER_APP_PROFILE_STRING': 'Internet Explorer', 'WXDRIVE_START_ARGS': '--wxdrive-setting=0 --disable-gpu --disable-software-rasterizer --enable-features=NetworkServiceInProcess', 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC', 'WINDIR': 'C:\\Windows', 'APPDATA': 'C:\\Users\\47576\\AppData\\Roaming', 'HOMEDRIVE': 'C:', 'SYSTEMDRIVE': 'C:', 'NUMBER_OF_PROCESSORS': '8', 'PROCESSOR_LEVEL': '6', 'COMMONPROGRAMW6432': 'C:\\Program Files\\Common Files', 'OS': 'Windows_NT', 'PUBLIC': 'C:\\Users\\Public', 'USERPROFILE': 'C:\\Users\\47576'}
>>>

 ##os.linesep  #给出当前平台使用的行终止符

>>> os.linesep
'\n'      #linux

>>> os.linesep
'\r\n'    #windows

##os.path.abspath(path) #显示当前绝对路径

>>> os.path.abspath("")   #不允许为空,括号内是什么结尾就是什么,不管文件存不存在
'/root'
>>> os.path.abspath('asfsafd')
'/root/asfsafd'

 

##os.path.dirname(path)   #显示该路径的父目录,不管路径是否正确

>>> os.path.dirname('/adas/afsdf/safsad/sadfsda')
'/adas/afsdf/safsad'
 

 

##os.path.basename(path)    #返回该路径的最后一个目录或文件,若path以\  或/结尾,返回空值

>>> os.path.basename('/adas/afsdf/safsad/sadfsda')
'sadfsda'

 

##os.path.isfile(path) #如果path存在且是一个文件,则返回True

>>> os.path.isfile("/sadfsad")
False
>>> os.path.isfile("/root")
False
>>> os.path.isfile("/root/aa")
False
>>> os.path.isfile("/root/aa.ini")
False
>>> os.listdir("/root")
['.bash_logout', '.bash_profile', '.bashrc', '.cshrc', '.tcshrc', 'anaconda-ks.cfg', '.bash_history', '.pki', '.ansible', '.lesshst', '.cache', '.viminfo', '.Xauthority', 'bb', 'b.ini']
>>> os.path.isfile("/root/b.ini")
True
 

##os.path.isdir(path) #如果path是一个目录,则返回True

>>> os.listdir("/root")
['.bash_logout', '.bash_profile', '.bashrc', '.cshrc', '.tcshrc', 'anaconda-ks.cfg', '.bash_history', '.pki', '.ansible', '.lesshst', '.cache', '.viminfo', '.Xauthority', 'bb', 'b.ini']
>>> os.path.isfile("/root/b.ini")
True
>>> os.path.isdir("/root/b.ini")
False
>>> os.path.isdir("/root/")
True
>>> os.path.isdir("/root")
True
>>> os.path.isdir("/safasdf")
False
 

##os.stat()   #返回文件或目录信息


>>> os.stat("/asfasfsadf")
Traceback (most recent call last):
  File "", line 1, in
OSError: [Errno 2] No such file or directory: '/asfasfsadf'
>>> os.stat("/root")
posix.stat_result(st_mode=16744, st_ino=67155137, st_dev=64768L, st_nlink=6, st_uid=0, st_gid=0, st_size=251, st_atime=1591767430, st_mtime=1591767425, st_ctime=1591767425)
>>> os.stat("/root/b.ini")
posix.stat_result(st_mode=33188, st_ino=67759104, st_dev=64768L, st_nlink=1, st_uid=0, st_gid=0, st_size=427, st_atime=1591610273, st_mtime=1591610273, st_ctime=1591767425)
>>> os.stat("/root/asdfsd")
Traceback (most recent call last):
  File "", line 1, in
OSError: [Errno 2] No such file or directory: '/root/asdfsd'
 

##os.path.split(path)  #将path分割为路径名和文件名,如果最后一个是目录也会将目录作为文件名分割,并且不会判断其是否存在

>>> os.path.split("/fasfd/safdsf/sdfsdwrqwer")
('/fasfd/safdsf', 'sdfsdwrqwer')
 

##os.path.join(path,name)  #链接目录与文件名或目录名,结果为path/name

>>> os.path.join("/fasfd/safdsf/sdfsdwrqwer","safdsfwqervc")
'/fasfd/safdsf/sdfsdwrqwer/safdsfwqervc'
 

你可能感兴趣的:(Python-OS模块学习笔记)