os模块
在自动化测试中,经常需要查找操作文件,比如查找配置文件(从而读取配置文件的信息),查找测试报告等等,经常会对大量文件和路径进行操作,这就依赖os模块
1. os.getcwd()
功能:查看当前所在路径
import os
print(os.getcwd())
2. os.listdir()
列举目录下所有的文件,返回的是列表类型
import os
print(os.listdir("c:\file"))
3. os.path.abspath(path)
功能:返回path的绝对路径
import os
print(os.path.abspath("."))
4. os.path.split(path)
功能: 将路径分解为(文件夹,文件名),返回的是元组类型
注意:若路径字符串最后一个字符是,则只有文件夹部分有值,若路径字符串中均无,则只有文件名部分有值,若路径字符串有\且不在最后,则文件夹和文件名都有值,且返回的结果不包括\
import os
print(os.path.split(r"D:\python\file\hello.py"))
#结果
('D:\python\file','hello.py')
print(os.path.split("."))
#结果
('','.')
os.path.split('D:\\pythontest\\ostest\\')
#结果
('D:\\pythontest\\ostest', '')
os.path.split('D:\\pythontest\\ostest')
('D:\\pythontest', 'ostest')
5. os.path.join(path1,path2,…)
将path进行组合,若其中有绝对路径,则之前的path将会被删除.
>>> import os
>>> os.path.join(r"d:\python\test",'hello.py')
'd:\pyhton\test\hello.py'
>>> os.path.join(r"d:\pyhton\test\hello.py",r"d:\pyhton\test\hello2.py")
'd:\pyhton\test\hello2.py'
6. os.path.dirname(path)
返回path中文件夹部分,不包括"\"
>>> import os
>>> os.path.dirname(r"d:\pyhton\test\hello.py")
'd:\pyhton\test'
>>> os.path.dirname(".")
''
>>> os.path.dirname(r"d:\pyhton\test\")
'd:\pyhton\test'
>>> os.path.dirname(r"d:\pyhton\test")
test
7. os.path.basename(path)
功能:返回path中文件名
>>> import os
>>> os.path.basename(r"d:\pyhton\test\hello.py")
'hello.py'
>>> os.path.basename(".")
'.'
>>> os.path.basename(r"d:\pyhton\test\")
''
>>> os.path.basename(r"d:\pyhton\test")
'test'
8. os.path.getsize(path)
功能: 获取文件的大小,若是文件夹则返回0python2.7
>>> import os
>>> os.path.getsize(r"d:\pyhton\test\hello.py")
38L
>>> os.path.getsize(r"d:\pyhton\test")
0L
9. os.path.exists(path)
>>> import os
>>> os.listdir(os.getcwd())
['hello.py','test.txt']
>>> os.path.exists(r"d:\python\test\hello.py")
True
>>> os.path.exists(r"d:\python\test\hello1.py")
False
10. 获取windows桌面路径
import winreg
# 获取桌面路径
def get_desktop():
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
return winreg.QueryValueEx(key, 'Desktop')[0]