Article Directory
- Brief introduction
- 1. Return type of operating system: posix is linux operating system, nt is the windows operating system
- 2. Details of the operating system
- 3. The system environment variables
- 4 determines whether the absolute path
- 5. Get the current path
- 6. The three ways to generate absolute path
- 7. Gets the directory or file name
- 8. Return all the file names and directory names in the specified directory, a list is returned
- 9. separation and file name extension
- 10. The directory name and file name separated
- 11. Create a directory [mkdir / mkdir -p]
- 12. You can delete empty directories recursively multi-layer, if there are files in the directory can not be deleted
- 13. Create File Delete File
- 14. Rename the file
- 15. whether a file or directory exists
- 16. determine whether the file or directory
- 17. To change the current directory to the specified directory
- 18. File Information
Brief introduction
os module provides most of the functionality of the operating system interface functions. When the module is introduced into the os, it will be adaptive to a different operating system platforms, the corresponding operation according to different platforms, the python programming, and often files, directories dealing with time and can become os module, this section os module provides functions will be detailed interpretation
1. Return type of operating system: posix is linux operating system, nt is the windows operating system
print(os.name)
print('Linux' if os.name == 'posix' else 'Windows')
posix
Linux
2. Details of the operating system
info = os.uname()
print(info)
print(info.sysname)
print(info.nodename)
posix.uname_result(sysname='Linux', nodename='foundation1.ilt.example.com', release='3.10.0-514.el7.x86_64', version='#1 SMP Wed Oct 19 11:24:13 EDT 2016', machine='x86_64')
Linux
foundation1.ilt.example.com
3. The system environment variables
print(os.environ)
print(os.environ.get('PATH')) #通过key值获取环境变量对应的value值
environ({'PATH': '/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin:/home/kiosk/.local/bin:/home/kiosk/bin', 'XAUTHORITY': '/run/gdm/auth-for-kiosk-VxJi8Q/database', 'IMSETTINGS_MODULE': 'none', 'HISTCONTROL': 'ignoredups', 'XMODIFIERS': '@im=ibus', 'GDMSESSION': 'gnome-classic', 'DBUS_SESSION_BUS_ADDRESS': 'unix:abstract=/tmp/dbus-Pz5VvDs6Nd,guid=dda5a3ee1f3848808f16852b5d004efd', 'XDG_CURRENT_DESKTOP': 'GNOME-Classic:GNOME', 'MAIL': '/var/spool/mail/kiosk', 'SSH_AGENT_PID': '1616', 'LD_LIBRARY_PATH': '.:', 'SESSION_MANAGER': 'local/unix:@/tmp/.ICE-unix/1446,unix/unix:/tmp/.ICE-unix/1446', 'USERNAME': 'kiosk', 'LOGNAME': 'kiosk', 'PWD': '/home/kiosk/PycharmProjects/2019python', 'PYCHARM_HOSTED': '1', 'WINDOWID': '31457287', 'PYTHONPATH': '/home/kiosk/PycharmProjects/2019python', 'LESSOPEN': '||/usr/bin/lesspipe.sh %s', 'SHELL': '/bin/bash', 'QT_GRAPHICSSYSTEM_CHECKED': '1', 'GNOME_DESKTOP_SESSION_ID': 'this-is-deprecated', 'IMSETTINGS_INTEGRATE_DESKTOP': 'yes', 'XDG_SESSION_DESKTOP': 'gnome-classic', 'LS_COLORS': 'rs=0:di=38;5;27:ln=38;5;51:mh=44;38;5;15:pi=40;38;5;11:so=38;5;13:do=38;5;5:bd=48;5;232;38;5;11:cd=48;5;232;38;5;3:or=48;5;232;38;5;9:mi=05;48;5;232;38;5;15:su=48;5;196;38;5;15:sg=48;5;11;38;5;16:ca=48;5;196;38;5;226:tw=48;5;10;38;5;16:ow=48;5;10;38;5;21:st=48;5;21;38;5;15:ex=38;5;34:*.tar=38;5;9:*.tgz=38;5;9:*.arc=38;5;9:*.arj=38;5;9:*.taz=38;5;9:*.lha=38;5;9:*.lz4=38;5;9:*.lzh=38;5;9:*.lzma=38;5;9:*.tlz=38;5;9:*.txz=38;5;9:*.tzo=38;5;9:*.t7z=38;5;9:*.zip=38;5;9:*.z=38;5;9:*.Z=38;5;9:*.dz=38;5;9:*.gz=38;5;9:*.lrz=38;5;9:*.lz=38;5;9:*.lzo=38;5;9:*.xz=38;5;9:*.bz2=38;5;9:*.bz=38;5;9:*.tbz=38;5;9:*.tbz2=38;5;9:*.tz=38;5;9:*.deb=38;5;9:*.rpm=38;5;9:*.jar=38;5;9:*.war=38;5;9:*.ear=38;5;9:*.sar=38;5;9:*.rar=38;5;9:*.alz=38;5;9:*.ace=38;5;9:*.zoo=38;5;9:*.cpio=38;5;9:*.7z=38;5;9:*.rz=38;5;9:*.cab=38;5;9:*.jpg=38;5;13:*.jpeg=38;5;13:*.gif=38;5;13:*.bmp=38;5;13:*.pbm=38;5;13:*.pgm=38;5;13:*.ppm=38;5;13:*.tga=38;5;13:*.xbm=38;5;13:*.xpm=38;5;13:*.tif=38;5;13:*.tiff=38;5;13:*.png=38;5;13:*.svg=38;5;13:*.svgz=38;5;13:*.mng=38;5;13:*.pcx=38;5;13:*.mov=38;5;13:*.mpg=38;5;13:*.mpeg=38;5;13:*.m2v=38;5;13:*.mkv=38;5;13:*.webm=38;5;13:*.ogm=38;5;13:*.mp4=38;5;13:*.m4v=38;5;13:*.mp4v=38;5;13:*.vob=38;5;13:*.qt=38;5;13:*.nuv=38;5;13:*.wmv=38;5;13:*.asf=38;5;13:*.rm=38;5;13:*.rmvb=38;5;13:*.flc=38;5;13:*.avi=38;5;13:*.fli=38;5;13:*.flv=38;5;13:*.gl=38;5;13:*.dl=38;5;13:*.xcf=38;5;13:*.xwd=38;5;13:*.yuv=38;5;13:*.cgm=38;5;13:*.emf=38;5;13:*.axv=38;5;13:*.anx=38;5;13:*.ogv=38;5;13:*.ogx=38;5;13:*.aac=38;5;45:*.au=38;5;45:*.flac=38;5;45:*.mid=38;5;45:*.midi=38;5;45:*.mka=38;5;45:*.mp3=38;5;45:*.mpc=38;5;45:*.ogg=38;5;45:*.ra=38;5;45:*.wav=38;5;45:*.axa=38;5;45:*.oga=38;5;45:*.spx=38;5;45:*.xspf=38;5;45:', 'SHLVL': '3', 'QT_PLUGIN_PATH': '/usr/lib64/kde4/plugins:/usr/lib/kde4/plugins', 'QT_IM_MODULE': 'ibus', 'HISTSIZE': '1000', 'TERM': 'xterm-256color', 'XFILESEARCHPATH': '/usr/dt/app-defaults/%L/Dt', 'LANG': 'en_US.utf8', 'XDG_SESSION_ID': '1', 'DISPLAY': ':0', '_': '../jre/jre/bin/java', 'GDM_LANG': 'en_US.utf8', 'PYTHONIOENCODING': 'UTF-8', 'DESKTOP_SESSION': 'gnome-classic', 'GPG_AGENT_INFO': '/run/user/1000/keyring/gpg:0:1', 'USER': 'kiosk', 'XDG_MENU_PREFIX': 'gnome-', 'WINDOWPATH': '1', 'VTE_VERSION': '3804', 'XDG_SEAT': 'seat0', 'SSH_AUTH_SOCK': '/run/user/1000/keyring/ssh', 'PYTHONUNBUFFERED': '1', 'HOSTNAME': 'foundation1.ilt.example.com', 'NLSPATH': '/usr/dt/lib/nls/msg/%L/%N.cat', 'GNOME_SHELL_SESSION_MODE': 'classic', 'KDEDIRS': '/usr', 'XDG_RUNTIME_DIR': '/run/user/1000', 'XDG_VTNR': '1', 'HOME': '/home/kiosk'})
/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin:/home/kiosk/.local/bin:/home/kiosk/bin
4 determines whether the absolute path
print(os.path.isabs('/tmp/ffff'))
print(os.path.isabs('hello.jog'))
True
False
5. Get the current path
print(os.getcwd())
/home/kiosk/PycharmProjects/2019python
6. The three ways to generate absolute path
print(os.path.abspath('hello.png'))
print(os.path.join(os.path.abspath('.'),'hello.jpg')) ## .表示当前路径
print(os.path.join('/home/kiosk','hello.jpg'))
/home/kiosk/PycharmProjects/2019python/hello.png
/home/kiosk/PycharmProjects/2019python/hello.jpg
/home/kiosk/hello.jpg
7. Gets the directory or file name
filename = '/1234/year/month/day/hello.jpg'
print(os.path.basename(filename))
print(os.path.dirname(filename))
hello.jpg
/1234/year/month/day
8. Return all the file names and directory names in the specified directory, a list is returned
print(os.listdir('img'))
['file1']
9. separation and file name extension
print(os.path.splitext('hello.jpg'))
10. The directory name and file name separated
print(os.path.split('/tmp/hello/hello.jpg'))
11. Create a directory [mkdir / mkdir -p]
os.mkdir('img')
os.makedirs('img/file1/file2')
You can not recursively delete a directory, delete layer by layer
os.rmdir('img')
OSError: [Errno 39] Directory not empty: 'img'
12. You can delete empty directories recursively multi-layer, if there are files in the directory can not be deleted
os.removedirs('img/file1/file2')
13. Create File Delete File
os.mknod('00_ok.txt')
os.remove('00_ok.txt')
14. Rename the file
os.rename('data.txt','data1.txt')
15. whether a file or directory exists
print(os.path.exists('ips.txtyyyy'))
print(os.path.exists('/home/kiosk/PycharmProjects/2019python/ips.txt'))
False
True
16. determine whether the file or directory
print(os.path.isfile('ips.txt'))
print(os.path.isdir('img'))
17. To change the current directory to the specified directory
print(os.getcwd())
path='/tmp'
os.chdir(path)
print(os.getcwd())
/home/kiosk/PycharmProjects/2019python
/tmp
18. File Information
Access: Time file was last accessed; When the editor to open the file, using the cat, more, less, grep, sed reads the contents of the file will refresh time [Access using ls -lu can read the current Access time ]
Modify: contents of the file was last modified time; When modifying the file content Modify time will refresh
Usage ls -l command displays the last time Modify]
Change: file attribute was last modified time, perform mv, chmod, chgrp command to a file or directory you will refresh time [Change can be viewed using the ls -lc last time] Change
------ ------------------------ ---------------- practice
in the current directory new directory img, which contains multiple files, the file names are different (X4G5.png)
a list of all currently img suffix name changed to the end of .jpg .png
import random
import string
import os
def gen_code(len=4):
# 随机生成4位验证码
li = random.sample(string.ascii_letters+string.digits,len)
return ''.join(li)
def create_file():
# 随机生成100个验证码
li = {gen_code() for i in range(100)}
os.mkdir('img')
for name in li:
os.mknod('img/' + name + '.png')
create_file()
def modify_suffix(dirname,old_suffix,new_suffix):
"""
:param dirname:操作的目录
:param old_suffix: 之前的后缀名
:param new_suffix: 新的后缀名
:return:
"""
# 1.判断查找的目录是否存在,如果不存在,报错
if os.path.exists(dirname):
# 2.找出所有以old_suffix(.png)结尾的文件
pngfile = [filename for filename in os.listdir(dirname)
if filename.endswith(old_suffix)]
# 3.将后缀名和文件名分开,留下文件名
basefiles = [os.path.splitext(filename)[0]
for filename in pngfile]
# 4.重命名文件
for filename in basefiles:
oldname = os.path.join(dirname,filename+old_suffix)
newname = os.path.join(dirname,filename+new_suffix)
os.rename(oldname,newname)
print('%s命名为%s成功' %(oldname,newname))
else:
print('%s不存在,不能操作...' %(dirname))
modify_suffix('redhat','.jpg','.png')