(Regular Expression)一种文本模式,描述在搜索文本时要匹配的一个或多个字符串
数据验证
文本扫描
文本提取
文本替换
文本分割
字面值:普通字符
需转义:\ ^ $ . | ? * + () [] {}
元字符
单字,预定义元字符 . 除\n外的所有字符
\d 数字,等同于[0-9]
\D 非数字,等同于 [^0-9 ]
\s 空白字符 \t\n\r\f\v
\S 非空白字符[^\t\n\r\f\v]
\w 字母数字[ a- zA-Z0-9_]
\W 非字母数字[^ a-zA-Z0-9_]]
批量备选 |yes |no
贪婪与非贪婪:
贪婪(默认):尽量匹配最大的范围结果
非贪婪:尽量匹配最小范围结果
方法:量词后追加?
例: ??
*?
+?
边界匹配 ^ 行首
$ 行尾
\b 单词边界
\B 非单词边界
\A 输入开头
\Z输入结尾
注:或因上下文差异有不同表现
模式对象,表现编译后的正则表达式(编译为字节码并缓存)
编译: re.compile( r'模式')
.findall() 查找所有非重叠匹配项
返回list
查找一个字符串的年龄
>>>import re
>>>text = 'Tom is 8 years old .Mike is 25 years old.'
>>>text = "Tom is 8 years old .Mike is 25 years old."
>>>pattern = re.compile('\d+')
>>>pattern.findall(text)
['8', '25']
>>>text
'Tom is 8 years old .Mike is 25 years old.'
>>>re.findall('\d+',text)
['8', '25']
定义模式: re.compile( r’模式’)
>>>import re
>>>s = "\\author:Tom"
>>>pattern = re.compile('\\author')
>>>pattern = re.compile('\\\\author')
>>>pattern.findall(s)
['\\author']
>>>pattern = re.compile(r'\\author')
>>>pattern.findall(s)
['\\author']
查看是否匹配
import re
text = 'Tom is 8 years old. Mike is 23 years old. Peter is 87 years old.'
pattern = re.compile(r'\d+')
pattern.findall(text)
['8', '23', '87']
p_name = re.compile(r'[A-Z]\w+')
p_name.findall(text)
['Tom', 'Mike', 'Peter']
.match(string[,pos[,endpos]] 使用match时匹配,仅从起始位置,需要指定匹配下标
返回MatchObject
>>>import re
>>>pattern = re.compile(r'')
>>>text = ''
>>>pattern.match(text)
<_sre.SRE_Match object; span=(0, 6), match=''>
>>>text2 = ' '
>>>pattern.match(text2)
>>>pattern.match(text2,1)
<_sre.SRE_Match object; span=(1, 7), match=''>
.search(string[,[pos[,enpos]]) 任意位置搜索
返回MatchObject
>>>import re
>>>text = "Tom is 8 years old.Mike is 35 years old. Peter is 87 years old."
>>>p1 = re.compile(r'\d+')
>>>p2 = re.compile(r'[A-Z]\w+')
>>>p1.match(text)
>>>p2.match(text)
<_sre.SRE_Match object; span=(0, 3), match='Tom'>
>>>p1.search(text)
<_sre.SRE_Match object; span=(9, 10), match='8'>
.finditer() 查找所有匹配项,返回包括MatchObject元素的迭代器
>>>it = p1.finditer(text)
>>>for m in it:
… print(m)
…
<_sre.SRE_Match object; span=(9, 10), match='8'>
<_sre.SRE_Match object; span=(32, 34), match='35'>
<_sre.SRE_Match object; span=(58, 60), match='87'>
主要功能:表现被匹配的模式
>>>import re
>>>text = 'Tom is 8 years old. Jerry is 23 years old.'
>>>pattern = re.compile(r'\d+')
>>>pattern.findall(text)
['8', '23']
>>>pattern = re.compile(r'(\d+).*?(\d+)')
>>>m = pattern.search(text)
>>>m
<_sre.SRE_Match object; span=(7, 33), match='8 years old. Jerry is 23'>
>>>m.group()
'8 years old. Jerry is 23'
>>>m.group(0)
'8 years old. Jerry is 23'
>>>m.group(1)
'8'
>>>m.group(2)
'23'
>>>m.start(1)
7
>>>m.end(1)
8
.start() 返回特定分组的起始索引
.end() 返回特定分组的终止索引
.span() 返回特定分组的起止索引分组
.groupdict()以字典表形式返回分组名及结果
>>>import re
>>>pattern = re.compile(r'(\w+)(\w+)')
>>>text = "Beautiful is better than ugily."
>>>it = pattern.finditer(text)
>>>for m in it:
… print(m.group())
…
Beautiful
is
better
than
ugily
场景:从匹配模式中提取信息
创建子正则以应用量词
限制备选项范围
>>>import re
>>>re.search(r'ab+c','ababc')
<_sre.SRE_Match object; span=(2, 5), match='abc'>
>>>re.search(r'(ab)+c','ababc')
<_sre.SRE_Match object; span=(0, 5), match='ababc'>
限制备选项范围
>>>import re
>>>re.search(r'Center|re','Center')
<_sre.SRE_Match object; span=(0, 6), match='Center'>
>>>re.search(r'Center|re','Centre')
<_sre.SRE_Match object; span=(4, 6), match='re'>
>>>re.search(r'Cent(er|re)','Centre')
<_sre.SRE_Match object; span=(0, 6), match='Centre'>
>>>re.search(r'Cent(er|re)','Centre')
<_sre.SRE_Match object; span=(0, 6), match='Centre'>
>>>re.search(r'Cent(er|re)','Center')
<_sre.SRE_Match object; span=(0, 6), match='Center'>
重用正则模式中提取的内容
>>>re.search(r'(\w+) \1', 'hello world')
>>>re.search(r'(\w+)\1','hello hello world')
<_sre.SRE_Match object; span=(2, 4), match='ll'>
声明(模式)
(?模式)
引用
>>>import re
>>>text = "Tom:98"
>>>pattern = re.compile(r'(\w+):(\d+)')
>>>m = pattern.search(text)
>>>m.group()
'Tom:98'
>>>m.groups()
('Tom', '98')
>>>m.groups(1)
('Tom', '98')
>>>pattern = re.compile(r'(?P\w+):(?P\d+)')
>>>m = pattern.search(text)
>>>m.group()
'Tom:98'
>>>m.group(1)
'Tom'
>>>m.group('name')
'Tom'
>>>m.group('score')
'98'
字符串操作:.split(string,maxsplit = 0) 分割字符串
>>>import re
>>>text = 'Beautiful is better than ugly.\n Explicit is better than implicit.\n Simple is better than complex.'
>>>re.split(r'\n',text)
['Beautiful is better than ugly.', ' Explicit is better than implicit.', ' Simple is better than complex.']
>>>re.split(r'\W','Good morning')
['Good', 'morning']
>>>re.split(r'-','Good-morning')
['Good', 'morning']
>>>re.split(r'(-)','Good-morning')
['Good', '-', 'morning']
text
'Beautiful is better than ugly.\n Explicit is better than implicit.\n Simple is better than complex.'
re.split(r'\n',text,2)
['Beautiful is better than ugly.', ' Explicit is better than implicit.', ' Simple is better than complex.']
re.split(r'\n',text,1)
['Beautiful is better than ugly.', ' Explicit is better than implicit.\n Simple is better than complex.']
>>>ords = 'ORD000\nORD001\nORD003'
>>>re.sub(r'\d+','-',ords)
'ORD-\nORD-\nORD-'
>>>text = 'Beautiful is *better* than ugly.'
>>>re.sub(r'\*(.*?)\*','',text)
'Beautiful is than ugly.'
>>>re.sub(r'\*(.*?)\*','\g<1>',text)
'Beautiful is better than ugly.'
给编组取名称,然后以名称来引用
>>> ords
'ORD000\nORD001\nORD003'
>>>re.sub(r'([A-Z]+)(\D+)','\G<2>-\g<1>',ords)
'\\G<2>-OR000\n\\G<2>-OR001\n\\G<2>-OR003'
>>>re.sub(r'([A-Z]+)(\d+)','\g<2>-\g<1>',ords)
'000-ORD\n001-ORD\n003-ORD'
>>>re.subn(r'([A-Z]+)(\d+)','\g<2>-\g<1>',ords)
('000-ORD\n001-ORD\n003-ORD', 3)
re.I 忽略大小写
re.M匹配多行
re.S 指定“.”匹配所有字符,包括\n
>>>import re
>>>text = 'Python python PYTHON'
>>>re.search(r'python',text)
<_sre.SRE_Match object; span=(7, 13), match='python'>
>>>re.findall(r'python',text)
['python']
>>>re.findall(r'python',text,re.I)
['Python', 'python', 'PYTHON']
>>>re.findall(r'^','\n')
[]
>>>re.findall(r'','\n',re.M)
['']
>>>re.findall(r'\d(.)','1\ne')
[]
>>>re.findall(r'\d(.)','1\ne',re.S)
['\n']
re.purge()
re.findall(r'^','^python^')
['']
re.findall(re.escape('^'),'^python^')
['^', '^']
命令行工具
Shell脚本
系统管理
sys 提供一组功能映射Python运行时的操作系统
os 提供跨品台可移植的操作系统编程接口
os.path 提供文件及目录工具的可移植编程接口
sys.platform 正在运行的操作系统的版本
sys.version python版本
sys.path 模块搜索路径
sys.modules
import sys
>>>sys.platform
'win32'
>>>sys.version
'3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)]'
>>>sys.path
['D:\\Pycharm\\PyCharm 2019.1.3\\helpers\\pydev', 'D:\\Pycharm\\PyCharm 2019.1.3\\helpers\\pycharm_display', 'D:\\Pycharm\\PyCharm 2019.1.3\\helpers\\third_party\\thriftpy', 'D:\\Pycharm\\PyCharm 2019.1.3\\helpers\\pydev', 'E:\\python01\\venv\\Scripts\\python36.zip', 'D:\\Program Files\\Python36\\DLLs', 'D:\\Program Files\\Python36\\lib', 'D:\\Program Files\\Python36', 'E:\\python01\\venv', 'E:\\python01\\venv\\lib\\site-packages', 'E:\\python01\\venv\\lib\\site-packages\\setuptools-40.8.0-py3.6.egg', 'E:\\python01\\venv\\lib\\site-packages\\pip-19.0.3-py3.6.egg', 'D:\\Pycharm\\PyCharm 2019.1.3\\helpers\\pycharm_matplotlib_backend', 'E:\\python01', 'E:/python01']
sys.exc_info() 获取最后一次异常细节
traceback.print_tb(sys.exc_info()[2])
>>>import sys
>>>try:
… raise KeyError
…except:
… print('有错误发生!')
…
有错误发生!
>>>try:
… raise KeyError('错误的键值!')
…except KeyError as e:
… print(e)
…
'错误的键值!'
>>>import traceback
>>>try:
… raise KeyError
…except:
… print(sys.exc_info())
…
(, KeyError(), )
>>>try:
… raise keyError
…except:
… print(sys.exc_info())
… traceback.print_tb(sys.exc_info()[2])
(, NameError("name 'keyError' is not defined",), )
File "", line 2, in
sys.stdin 标准输入流
sys.stdout 标准输出流
sys.stderr 标准错误流
>>>import sys
>>>sys.stdout.write('hello')
hello5
>>>print('请输入信息:');sys.stdin.readline()[:]
请输入信息:
>?Python
>>>print('请输入信息:');x = sys.stdin.readline()[:]
请输入信息:
>?Python
>>>x
'Python\n'
>>>sys.stderr.write('错误消息')
4
>>>sys.stderr.flush()
错误消息
import os
os.environ
environ({'ALLUSERSPROFILE': 'C:\\ProgramData', 'APPDATA': 'C:\\Users\\Lab527\\AppData\\Roaming', 'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files', 'COMMONPROGRAMFILES(X86)': 'C:\\Program Files (x86)\\Common Files', 'COMMONPROGRAMW6432': 'C:\\Program Files\\Common Files', 'COMPUTERNAME': 'DESKTOP-1D7G6UI', 'COMSPEC': 'C:\\WINDOWS\\system32\\cmd.exe', 'DRIVERDATA': 'C:\\Windows\\System32\\Drivers\\DriverData', 'FPS_BROWSER_APP_PROFILE_STRING': 'Internet Explorer', 'FPS_BROWSER_USER_PROFILE_STRING': 'Default', 'GOOGLE_API_KEY': 'AIzaSyCvk4foxTnm - gNIPY - WI5Hq - fiYN8zm4fw', 'GOOGLE_DEFAULT_CLIENT_ID': '793783891518 - b6tl35b6fjk3mid3aaag4d5egnj9dlf0.apps.googleusercontent.com', 'GOOGLE_DEFAULT_CLIENT_SECRET': 'XPnofOhGhHOYYrgTxhSSA8Jg', 'HOMEDRIVE': 'C:', 'HOMEPATH': '\\Users\\Lab527', 'IPYTHONENABLE': 'True', 'LOCALAPPDATA': 'C:\\Users\\Lab527\\AppData\\Local', 'LOGONSERVER': '\\\\DESKTOP-1D7G6UI', 'NUMBER_OF_PROCESSORS': '4', 'ONEDRIVE': 'C:\\Users\\Lab527\\OneDrive', 'OS': 'Windows_NT', 'PATH': 'E:\\python01\\venv\\Scripts;D:\\Program Files\\Python36\\Scripts\\;D:\\Program Files\\Python36\\;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;D:\\matlab2014a\\runtime\\win64;D:\\matlab2014a\\bin;D:\\matlab2014a\\polyspace\\bin;C:\\WINDOWS\\System32\\OpenSSH\\;C:\\Users\\Lab527\\AppData\\Local\\Microsoft\\WindowsApps;;C:\\Program Files (x86)\\SSH Communications Security\\SSH Secure Shell;D:\\Pycharm\\PyCharm 2019.1.3\\bin;', 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW', 'PROCESSOR_ARCHITECTURE': 'AMD64', 'PROCESSOR_IDENTIFIER': 'Intel64 Family 6 Model 94 Stepping 3, GenuineIntel', 'PROCESSOR_LEVEL': '6', 'PROCESSOR_REVISION': '5e03', 'PROGRAMDATA': 'C:\\ProgramData', 'PROGRAMFILES': 'C:\\Program Files', 'PROGRAMFILES(X86)': 'C:\\Program Files (x86)', 'PROGRAMW6432': 'C:\\Program Files', 'PROMPT': '(venv) $P$G', 'PSMODULEPATH': 'C:\\Program Files\\WindowsPowerShell\\Modules;C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\Modules', 'PUBLIC': 'C:\\Users\\Public', 'PYCHARM': 'D:\\Pycharm\\PyCharm 2019.1.3\\bin;', 'PYCHARM_DISPLAY_PORT': '61929', 'PYCHARM_HOSTED': '1', 'PYCHARM_MATPLOTLIB_INDEX': '0', 'PYCHARM_MATPLOTLIB_INTERACTIVE': 'true', 'PYDEVD_LOAD_VALUES_ASYNC': 'True', 'PYTHONIOENCODING': 'UTF-8', 'PYTHONPATH': 'D:\\Pycharm\\PyCharm 2019.1.3\\helpers\\pycharm_matplotlib_backend;D:\\Pycharm\\PyCharm 2019.1.3\\helpers\\pycharm_display;D:\\Pycharm\\PyCharm 2019.1.3\\helpers\\third_party\\thriftpy;D:\\Pycharm\\PyCharm 2019.1.3\\helpers\\pydev', 'PYTHONUNBUFFERED': '1', 'SESSIONNAME': 'Console', 'SYSTEMDRIVE': 'C:', 'SYSTEMROOT': 'C:\\WINDOWS', 'TEMP': 'C:\\Users\\Lab527\\AppData\\Local\\Temp', 'TMP': 'C:\\Users\\Lab527\\AppData\\Local\\Temp', 'USERDOMAIN': 'DESKTOP-1D7G6UI', 'USERDOMAIN_ROAMINGPROFILE': 'DESKTOP-1D7G6UI', 'USERNAME': 'Lab527', 'USERPROFILE': 'C:\\Users\\Lab527', 'VIRTUAL_ENV': 'E:\\python01\\venv', 'WINDIR': 'C:\\WINDOWS', '_OLD_VIRTUAL_PATH': 'D:\\Program Files\\Python36\\Scripts\\;D:\\Program Files\\Python36\\;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;D:\\matlab2014a\\runtime\\win64;D:\\matlab2014a\\bin;D:\\matlab2014a\\polyspace\\bin;C:\\WINDOWS\\System32\\OpenSSH\\;C:\\Users\\Lab527\\AppData\\Local\\Microsoft\\WindowsApps;;C:\\Program Files (x86)\\SSH Communications Security\\SSH Secure Shell;D:\\Pycharm\\PyCharm 2019.1.3\\bin;', '_OLD_VIRTUAL_PROMPT': '$P$G'})
os.getcwd()
'E:\\python01'
在project下添加新的directory name,在新的目录下创建新的文件file(data.txt),展示新建目录的信息列表。
>>>import os
>>>os.environ
environ({'ALLUSERSPROFILE': 'C:\\ProgramData', 'APPDATA': 'C:\\Users\\Lab527\\AppData\\Roaming', 'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files', 'COMMONPROGRAMFILES(X86)': 'C:\\Program Files (x86)\\Common Files', 'COMMONPROGRAMW6432': 'C:\\Program Files\\Common Files', 'COMPUTERNAME': 'DESKTOP-1D7G6UI', 'COMSPEC': 'C:\\WINDOWS\\system32\\cmd.exe', 'DRIVERDATA': 'C:\\Windows\\System32\\Drivers\\DriverData', 'FPS_BROWSER_APP_PROFILE_STRING': 'Internet Explorer', 'FPS_BROWSER_USER_PROFILE_STRING': 'Default', 'GOOGLE_API_KEY': 'AIzaSyCvk4foxTnm - gNIPY - WI5Hq - fiYN8zm4fw', 'GOOGLE_DEFAULT_CLIENT_ID': '793783891518 - b6tl35b6fjk3mid3aaag4d5egnj9dlf0.apps.googleusercontent.com', 'GOOGLE_DEFAULT_CLIENT_SECRET': 'XPnofOhGhHOYYrgTxhSSA8Jg', 'HOMEDRIVE': 'C:', 'HOMEPATH': '\\Users\\Lab527', 'IPYTHONENABLE': 'True', 'LOCALAPPDATA': 'C:\\Users\\Lab527\\AppData\\Local', 'LOGONSERVER': '\\\\DESKTOP-1D7G6UI', 'NUMBER_OF_PROCESSORS': '4', 'ONEDRIVE': 'C:\\Users\\Lab527\\OneDrive', 'OS': 'Windows_NT', 'PATH': 'E:\\python01\\venv\\Scripts;D:\\Program Files\\Python36\\Scripts\\;D:\\Program Files\\Python36\\;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;D:\\matlab2014a\\runtime\\win64;D:\\matlab2014a\\bin;D:\\matlab2014a\\polyspace\\bin;C:\\WINDOWS\\System32\\OpenSSH\\;C:\\Users\\Lab527\\AppData\\Local\\Microsoft\\WindowsApps;;C:\\Program Files (x86)\\SSH Communications Security\\SSH Secure Shell;D:\\Pycharm\\PyCharm 2019.1.3\\bin;', 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW', 'PROCESSOR_ARCHITECTURE': 'AMD64', 'PROCESSOR_IDENTIFIER': 'Intel64 Family 6 Model 94 Stepping 3, GenuineIntel', 'PROCESSOR_LEVEL': '6', 'PROCESSOR_REVISION': '5e03', 'PROGRAMDATA': 'C:\\ProgramData', 'PROGRAMFILES': 'C:\\Program Files', 'PROGRAMFILES(X86)': 'C:\\Program Files (x86)', 'PROGRAMW6432': 'C:\\Program Files', 'PROMPT': '(venv) $P$G', 'PSMODULEPATH': 'C:\\Program Files\\WindowsPowerShell\\Modules;C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\Modules', 'PUBLIC': 'C:\\Users\\Public', 'PYCHARM': 'D:\\Pycharm\\PyCharm 2019.1.3\\bin;', 'PYCHARM_DISPLAY_PORT': '61929', 'PYCHARM_HOSTED': '1', 'PYCHARM_MATPLOTLIB_INDEX': '0', 'PYCHARM_MATPLOTLIB_INTERACTIVE': 'true', 'PYDEVD_LOAD_VALUES_ASYNC': 'True', 'PYTHONIOENCODING': 'UTF-8', 'PYTHONPATH': 'D:\\Pycharm\\PyCharm 2019.1.3\\helpers\\pycharm_matplotlib_backend;D:\\Pycharm\\PyCharm 2019.1.3\\helpers\\pycharm_display;D:\\Pycharm\\PyCharm 2019.1.3\\helpers\\third_party\\thriftpy;D:\\Pycharm\\PyCharm 2019.1.3\\helpers\\pydev', 'PYTHONUNBUFFERED': '1', 'SESSIONNAME': 'Console', 'SYSTEMDRIVE': 'C:', 'SYSTEMROOT': 'C:\\WINDOWS', 'TEMP': 'C:\\Users\\Lab527\\AppData\\Local\\Temp', 'TMP': 'C:\\Users\\Lab527\\AppData\\Local\\Temp', 'USERDOMAIN': 'DESKTOP-1D7G6UI', 'USERDOMAIN_ROAMINGPROFILE': 'DESKTOP-1D7G6UI', 'USERNAME': 'Lab527', 'USERPROFILE': 'C:\\Users\\Lab527', 'VIRTUAL_ENV': 'E:\\python01\\venv', 'WINDIR': 'C:\\WINDOWS', '_OLD_VIRTUAL_PATH': 'D:\\Program Files\\Python36\\Scripts\\;D:\\Program Files\\Python36\\;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;D:\\matlab2014a\\runtime\\win64;D:\\matlab2014a\\bin;D:\\matlab2014a\\polyspace\\bin;C:\\WINDOWS\\System32\\OpenSSH\\;C:\\Users\\Lab527\\AppData\\Local\\Microsoft\\WindowsApps;;C:\\Program Files (x86)\\SSH Communications Security\\SSH Secure Shell;D:\\Pycharm\\PyCharm 2019.1.3\\bin;', '_OLD_VIRTUAL_PROMPT': '$P$G'})
>>>os.getcwd()
'E:\\python01'
>>>os.listdir()
['.idea', 'data.txt', 'data2.txt', 'data3.txt', 'db', 'ex_shelve.py', 'shelve_student_db.bak', 'shelve_student_db.dat', 'shelve_student_db.dir', 'venv']
>>>os.chdir('db')
>>>os.getcwd()
'E:\\python01\\db'
>>>os.listdir()
['data.txt.py']
>>>os.listdir(r'd:')
['$RECYCLE.BIN', '360安全浏览器下载', 'BaiduNetdiskDownload', 'bauduyun', 'CAJ', 'Chrome_71.0.3578.98_XiaZaiBa', 'DingDing', 'IE11-x64', 'iSee', 'matlab2014a', 'MicrosoftOffice_2007_XiTongZhiJia', 'MSOCache', 'Office', 'PDF编辑器', 'Program Files', 'Program Files (x86)', 'ps', 'Pycharm', 'Python', 'QMDownload', 'QQ', 'QQPCMgr', 'qqpcmgr_docpro', 'shenruanjian', 'System Volume Information', 'Teamviewr', 'visio', 'WinRAR', 'word2007', '搜狗输入法']
>>>os.listdir()
['data.txt.py']
>>>os.getpid()
331680
.system() Python脚本中运行shell命令
.popen() 运行命令并连接输入输出流
列举当前信息
>>>os.popen('dir /b')
显示add.py原文件的信息
>>>os.popen('type add.py')
ϵͳ�Ҳ���ָ�����ļ���
>>>os.popen('type add.py')
ϵͳ�Ҳ���ָ�����ļ���
>>>txt = os.popen('dir /b').read()
>>>txt
'360安全浏览器下载\nBaiduNetdiskDownload\nbauduyun\nCAJ\nChrome_71.0.3578.98_XiaZaiBa\nDingDing\nIE11-x64\niSee\nmatlab2014a\nMicrosoftOffice_2007_XiTongZhiJia\nOffice\nPDF编辑器\nProgram Files\nProgram Files (x86)\nps\nPycharm\nPython\nQMDownload\nQQ\nshenruanjian\nTeamviewr\nvisio\nWinRAR\nword2007\n搜狗输入法\n'
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190917210942330.png)
>>>import os
>>>os.environ
environ({'ALLUSERSPROFILE': 'C:\\ProgramData', 'APPDATA': 'C:\\Users\\Lab527\\AppData\\Roaming', 'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files', 'COMMONPROGRAMFILES(X86)': 'C:\\Program Files (x86)\\Common Files', 'COMMONPROGRAMW6432': 'C:\\Program Files\\Common Files', 'COMPUTERNAME': 'DESKTOP-1D7G6UI', 'COMSPEC': 'C:\\WINDOWS\\system32\\cmd.exe', 'DRIVERDATA': 'C:\\Windows\\System32\\Drivers\\DriverData', 'FPS_BROWSER_APP_PROFILE_STRING': 'Internet Explorer', 'FPS_BROWSER_USER_PROFILE_STRING': 'Default', 'GOOGLE_API_KEY': 'AIzaSyCvk4foxTnm - gNIPY - WI5Hq - fiYN8zm4fw', 'GOOGLE_DEFAULT_CLIENT_ID': '793783891518 - b6tl35b6fjk3mid3aaag4d5egnj9dlf0.apps.googleusercontent.com', 'GOOGLE_DEFAULT_CLIENT_SECRET': 'XPnofOhGhHOYYrgTxhSSA8Jg', 'HOMEDRIVE': 'C:', 'HOMEPATH': '\\Users\\Lab527', 'IPYTHONENABLE': 'True', 'LOCALAPPDATA': 'C:\\Users\\Lab527\\AppData\\Local', 'LOGONSERVER': '\\\\DESKTOP-1D7G6UI', 'NUMBER_OF_PROCESSORS': '4', 'ONEDRIVE': 'C:\\Users\\Lab527\\OneDrive', 'OS': 'Windows_NT', 'PATH': 'E:\\python01\\venv\\Scripts;D:\\Program Files\\Python36\\Scripts\\;D:\\Program Files\\Python36\\;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;D:\\matlab2014a\\runtime\\win64;D:\\matlab2014a\\bin;D:\\matlab2014a\\polyspace\\bin;C:\\WINDOWS\\System32\\OpenSSH\\;C:\\Users\\Lab527\\AppData\\Local\\Microsoft\\WindowsApps;;C:\\Program Files (x86)\\SSH Communications Security\\SSH Secure Shell;D:\\Pycharm\\PyCharm 2019.1.3\\bin;', 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW', 'PROCESSOR_ARCHITECTURE': 'AMD64', 'PROCESSOR_IDENTIFIER': 'Intel64 Family 6 Model 94 Stepping 3, GenuineIntel', 'PROCESSOR_LEVEL': '6', 'PROCESSOR_REVISION': '5e03', 'PROGRAMDATA': 'C:\\ProgramData', 'PROGRAMFILES': 'C:\\Program Files', 'PROGRAMFILES(X86)': 'C:\\Program Files (x86)', 'PROGRAMW6432': 'C:\\Program Files', 'PROMPT': '(venv) $P$G', 'PSMODULEPATH': 'C:\\Program Files\\WindowsPowerShell\\Modules;C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\Modules', 'PUBLIC': 'C:\\Users\\Public', 'PYCHARM': 'D:\\Pycharm\\PyCharm 2019.1.3\\bin;', 'PYCHARM_DISPLAY_PORT': '61929', 'PYCHARM_HOSTED': '1', 'PYCHARM_MATPLOTLIB_INDEX': '0', 'PYCHARM_MATPLOTLIB_INTERACTIVE': 'true', 'PYDEVD_LOAD_VALUES_ASYNC': 'True', 'PYTHONIOENCODING': 'UTF-8', 'PYTHONPATH': 'D:\\Pycharm\\PyCharm 2019.1.3\\helpers\\pycharm_matplotlib_backend;D:\\Pycharm\\PyCharm 2019.1.3\\helpers\\pycharm_display;D:\\Pycharm\\PyCharm 2019.1.3\\helpers\\third_party\\thriftpy;D:\\Pycharm\\PyCharm 2019.1.3\\helpers\\pydev', 'PYTHONUNBUFFERED': '1', 'SESSIONNAME': 'Console', 'SYSTEMDRIVE': 'C:', 'SYSTEMROOT': 'C:\\WINDOWS', 'TEMP': 'C:\\Users\\Lab527\\AppData\\Local\\Temp', 'TMP': 'C:\\Users\\Lab527\\AppData\\Local\\Temp', 'USERDOMAIN': 'DESKTOP-1D7G6UI', 'USERDOMAIN_ROAMINGPROFILE': 'DESKTOP-1D7G6UI', 'USERNAME': 'Lab527', 'USERPROFILE': 'C:\\Users\\Lab527', 'VIRTUAL_ENV': 'E:\\python01\\venv', 'WINDIR': 'C:\\WINDOWS', '_OLD_VIRTUAL_PATH': 'D:\\Program Files\\Python36\\Scripts\\;D:\\Program Files\\Python36\\;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;D:\\matlab2014a\\runtime\\win64;D:\\matlab2014a\\bin;D:\\matlab2014a\\polyspace\\bin;C:\\WINDOWS\\System32\\OpenSSH\\;C:\\Users\\Lab527\\AppData\\Local\\Microsoft\\WindowsApps;;C:\\Program Files (x86)\\SSH Communications Security\\SSH Secure Shell;D:\\Pycharm\\PyCharm 2019.1.3\\bin;', '_OLD_VIRTUAL_PROMPT': '$P$G'})
>>>os.getcwd()
'E:\\python01'
>>>os.listdir()
['.idea', 'data.txt', 'data2.txt', 'data3.txt', 'db', 'ex_shelve.py', 'shelve_student_db.bak', 'shelve_student_db.dat', 'shelve_student_db.dir', 'venv']
>>>os.chdir('db')
>>>os.getcwd()
'E:\\python01\\db'
>>>os.listdir()
['data.txt.py']
>>>os.listdir(r'd:')
['$RECYCLE.BIN', '360安全浏览器下载', 'BaiduNetdiskDownload', 'bauduyun', 'CAJ', 'Chrome_71.0.3578.98_XiaZaiBa', 'DingDing', 'IE11-x64', 'iSee', 'matlab2014a', 'MicrosoftOffice_2007_XiTongZhiJia', 'MSOCache', 'Office', 'PDF编辑器', 'Program Files', 'Program Files (x86)', 'ps', 'Pycharm', 'Python', 'QMDownload', 'QQ', 'QQPCMgr', 'qqpcmgr_docpro', 'shenruanjian', 'System Volume Information', 'Teamviewr', 'visio', 'WinRAR', 'word2007', '搜狗输入法']
>>>os.listdir()
['data.txt.py']
>>>os.getpid()
327920
>>>os.getpid()
327920
>>>os.getppid()
324276
pycharm下的terminal运行
切换到D盘:d:
显示D盘的信息:dir
进入到iso目录:cd iso
返回上级目录:cd …
以简洁的方式列出当前目录下的详细信息:dir /b
在python中显示D盘信息
>>>os.system('dir /b')
360��ȫ���������
BaiduNetdiskDownload
bauduyun
CAJ
Chrome_71.0.3578.98_XiaZaiBa
DingDing
IE11-x64
iSee
matlab2014a
MicrosoftOffice_2007_XiTongZhiJia
Office
PDF�༭��
在操作系统下(python控制台)完成一些关于文件和目录的典型操作
>>>import os
>>>os.getcwd()
'E:\\python01'
>>>os.chdir('db')
>>>os.getcwd()
'E:\\python01\\db'
>>>os.mkdir('test')
>>>os.listdir()
['data.txt.py', 'test']
>>>os.chdir('test')
>>>os.getcwd()
'E:\\python01\\db\\test'
>>>os.listdir()
[]
>>>open('info.txt','w',encoding = 'utf8').write('Hello')
5
>>>os.listdir()
['info.txt']
>>>os.rename('info.txt','detail.txt')
>>>os.listdir()
['detail.txt']**
>>>os.remove('detail.txt')
>>>os.chdir('..')
>>>os.getcwd()
'E:\\python01\\db'
>>>os.rmdir('test')
import os
os.sep
'\\'
os.pathsep
';'
os.curdir
'.'
os.pardir
'..'
>>>import os
>>>os.getcwd()
'E:\\python01'
>>>os.listdir()
['.idea', 'data.txt', 'data2.txt', 'data3.txt', 'db', 'ex_shelve.py', 'shelve_student_db.bak', 'shelve_student_db.dat', 'shelve_student_db.dir', 'venv']
>>>os.chdir('db')
>>>os.listdir()
['data.txt.py']
>>>os.path.isdir(r'd:\iso')
False
>>>import os
>>>os.getcwd()
'E:\\python01'
>>>os.listdir()
['.idea', 'data.txt', 'data2.txt', 'data3.txt', 'db', 'ex_shelve.py', 'shelve_student_db.bak', 'shelve_student_db.dat', 'shelve_student_db.dir', 'venv']
>>>os.chdir('db')
>>>os.listdir()
['data.txt.py']
>>>os.path.isdir(r'd:\iso')
False
>>>os.path.isfile(r'd:\add.py')
False
>>>os.path.exists(r'd:\isoo')
False
>>>os.path.split(r'c:\data\temp\data.txt')
('c:\\data\\temp', 'data.txt')
>>>name = r'c:\data\temp\data.txt'
>>>os.path.dirname(name)
'c:\\data\\temp'
>>>os.path.basename(name)
'data.txt'
>>>os.path.splitext(name)
('c:\\data\\temp\\data', '.txt')
>>>os.path.splitext(name)[1]
'.txt'
>>>os.path.join(r'c:\temp','product.csv')
'c:\\temp\\product.csv'
>>>os.sep
'\\'
>>>name
'c:\\data\\temp\\data.txt'
>>>os.path.split(name)
('c:\\data\\temp', 'data.txt')
>>>name.split()
['c:\\data\\temp\\data.txt']
>>>name.split(os.sep)
['c:', 'data', 'temp', 'data.txt']