python中的os模塊
前言
1、os是operation system(操作系統)的縮寫;os模塊就是python對操作系統操作接口的封裝。os模塊提供了多數操作系統的功能接口函數。(OS模塊提供了與操作系統進行交互的函數)
2、操作系統屬於Python的標准實用程序模塊。該模塊提供了使用依賴於操作系統的函數的便攜式方法。
3、在自動化測試中,經常需要查找操作文件,比如說查找配置文件(從而讀取配置文件的信息),查找測試報告(從而發送測試報告郵件),查找測試用例的Excel文件或者Yaml文件等。
os函數
1、當前路徑及路徑下的文件
os.getcwd() :查看當前所在路徑。【具體到當前腳本的上一級】
os.listdir(path) :列舉path目錄下的所有文件。返回的是列表類型。
import os os.getcwd() # 'D:\\pythontest\\ostest' os.listdir(os.getcwd()) #['hello.py', 'test.txt']
2、絕對路徑
os.path.abspath(path) :返回當前文件位置的絕對路徑。
os.path.realpath(path) :返回當前文件位置的絕對路徑。
注意:如果 os.path.abspath(.) 存在與已被定義的方法中,則返回的絕對路徑是調用該方法的模塊的絕對路徑,而不是方法的絕對路徑。
舉例1:
import os print(os.getcwd()) print(os.path.abspath('.')) print(os.path.abspath('..')) print(os.path.abspath('../..'))
運行結果:
舉例2:
import os print(os.getcwd())
print(os.path.realpath(__file__))
print(os.path.abspath(__file__))
運行結果:
3、查看指定文件路徑的文件夾路徑部分和文件名部分
os.path.split(path) :將指定文件的路徑分解為(文件夾路徑, 文件名),返回的數據類型是元組類型。
①若文件夾路徑字符串最后一個字符是\,則只有文件夾路徑部分有值;
②若路徑字符串中均無\,則只有文件名部分有值。
③若路徑字符串有\,且不在最后,則文件夾和文件名均有值。且返回的文件名的結果不包含\.
4、路徑拼接
os.path.join(path1, path2, ...) :將入參的path進行組合,若其中有絕對路徑,則之前的path將被刪除。
os.path.split('D:\\pythontest\\ostest\\Hello.py') # ('D:\\pythontest\\ostest', 'Hello.py') os.path.split('.') # ('', '.') os.path.split('D:\\pythontest\\ostest\\') # ('D:\\pythontest\\ostest', '') os.path.split('D:\\pythontest\\ostest') # ('D:\\pythontest', 'ostest') os.path.join('D:\\pythontest', 'ostest') # 'D:\\pythontest\\ostest' os.path.join('D:\\pythontest\\ostest', 'hello.py') # 'D:\\pythontest\\ostest\\hello.py' os.path.join('D:\\pythontest\\b', 'D:\\pythontest\\a') # 'D:\\pythontest\\a'
5、獲取路徑的文件夾路徑部分
os.path.dirname(path) :返回path中的文件夾路徑部分,且路徑結尾不包含'\'。【即返回文件的路徑(此路徑不包含文件名)】
os.path.dirname('D:\\pythontest\\ostest\\hello.py') # 'D:\\pythontest\\ostest' os.path.dirname('.') # '' os.path.dirname('D:\\pythontest\\ostest\\') # 'D:\\pythontest\\ostest' os.path.dirname('D:\\pythontest\\ostest') # 'D:\\pythontest'
6、獲取路徑的文件名
os.path.basename(path) :返回path中的文件名。
os.path.basename('D:\\pythontest\\ostest\\hello.py') # 'hello.py' os.path.basename('.') # '.' os.path.basename('D:\\pythontest\\ostest\\') # '' os.path.basename('D:\\pythontest\\ostest') # 'ostest'
7、查看文件時間
os.path.getmtime(path) :返回文件或文件夾的最后修改時間,從新紀元到訪問時的秒數。
os.path.getatime(path) :返回文件或文件夾的最后訪問時間,從新紀元到訪問時的秒數。
os.path.getctime(path) :返回文件或文件夾的創建時間,從新紀元到訪問時的秒數。
os.path.getmtime('D:\\pythontest\\ostest\\hello.py') # 1481695651.857048 os.path.getatime('D:\\pythontest\\ostest\\hello.py') # 1481687717.8506615 os.path.getctime('D:\\pythontest\\ostest\\hello.py') # 1481687717.8506615
8、查看文件大小
os.path.getsize(path) :返回文件的大小;若path入參值是一個文件夾路徑則返回0。
os.path.getsize('D:\\pythontest\\ostest\\hello.py') # 58L os.path.getsize('D:\\pythontest\\ostest') # 0L
9、查看文件是否存在
os.path.exists(path) :判斷文件或者文件夾是否存在,返回True 或 False。【文件或文件夾的名字不區分大小寫】
os.listdir(os.getcwd()) # ['hello.py', 'test.txt'] os.path.exists('D:\\pythontest\\ostest\\hello.py') # True os.path.exists('D:\\pythontest\\ostest\\Hello.py') # True os.path.exists('D:\\pythontest\\ostest\\Hello1.py') # False
10、os模塊中操作目錄以及文件的函數
os.mkdir('文件夾名') :新建文件夾;入參為目錄路徑,不可為文件路徑;(父目錄必須存在的情況下創建下一級文件夾)
os.rmdir('文件夾名') :刪除文件夾;入參為目錄路徑,不可為文件路徑
os.remove('文件路徑') :刪除文件;入參為文件路徑,不可為目錄路徑
os.makedirs('路徑及文件') :遞歸新建文件夾;可以連續創建該文件夾的多級目錄
os.path.isdir('路徑') :判斷入參路徑是否為文件夾,返回值為布爾值;是文件夾返回True,不是文件夾返回False
os.path.isfile('路徑') :判斷入參路徑是否為文件,返回值為布爾值;是文件返回True,不是文件返回False
11、os模塊中遍歷目錄數
一個遍歷目錄數的函數,它以一種深度優先的策略(depth-first)訪問指定的目錄。
os.walk(top=path,topdown=True,oneerror=None)
- 參數 top 表示需要遍歷的目錄樹的路徑。
- 參數 topdown 默認為 True ,表示首先返回根目錄樹下的文件,然后,再遍歷目錄樹的子目錄。 當topdown 的值為 False 時,則表示先遍歷目錄樹的子目錄,返回子目錄下的文件,最后返回根目錄下的文件。
- 參數 oneerror 的默認值為 None ,表示忽略文件遍歷時產生的錯誤;如果不為空,則提供一個自定義函數提示錯誤信息,后邊遍歷拋出異常。
os.walk() 函數的返回值是一個生成器(generator),每次遍歷的對象都是返回的是一個三元組 (root,dirs,files):該元組有3個元素,這3個元素分別表示每次遍歷的路徑名,目錄列表和文件列表。
- root 代表當前遍歷的目錄路徑,string類型。
- dirs 代表root路徑下的所有子目錄名稱;list類型,列表中的每個元素是string類型,代表子目錄名稱。
- files 代表root路徑下的所有子文件名稱;list類型,列表中的每個元素是string類型,代表子文件名稱。
實例1:
當前目錄結構如下:
代碼1:
import os from os.path import join home_path = "/home"
for (root, dirs, files) in os.walk(home_path): print(root) print(dirs) print(files) print("=" * 50)
運行結果:
/home ['root', 'zhang', 'li'] ['test.txt', 'hai.mp4'] ================================================== /home/root [] ['1.txt', '2.txt', '3.txt'] ================================================== /hoome/zhang [] ['zhang_1.mp4', 'zhang_2.mp4', 'zhang_3.mp4'] ================================================== /home/li [] [] ==================================================
解析:
一共三行:
第1行代表當前遍歷的目錄,我們稱為root目錄,
第2行代表root目錄下的子目錄列表,我們稱為dirs子目錄列表,
第3行代表root目錄下的子文件列表,我們稱為files子文件列表,
注意:上面的列表為空就代表當前遍歷的root目錄下沒有子目錄或者沒有子文件。
代碼2:遍歷home目錄下獲取所有的目錄和文件的絕對路徑
import os from os.path import join home_path = "/home"
for (root, dirs, files) in os.walk(home_path): for dir in dirs: print(join(root, dir)) for file in files: print(join(root, file))
運行結果:
/home /home/root /home/zhang /home/li /home/test.txt /home/hai.mp4 /home/root/1.txt /home/root/2.txt /home/root/3.txt /home/zhang/zhang_1.mp4 /home/zhang/zhang_2.mp4 /home/zhang/zhang_3.mp4
實例2:
import os
def walk(path): if not os.path.exists(path): return -1
for root,dirs,names in os.walk(path): for filename in names: print(os.path.join(root,filename)) # 路徑和文件名連接構成完整路徑
if __name__=='__main__': path = "C:\\Users\\Administrator\\Desktop\\2017-9-1" walk(path)
運行結果:
C:\Users\Administrator\Desktop\2017-9-1\2017-9-1.txt C:\Users\Administrator\Desktop\2017-9-1\2017-9-1storage.txt C:\Users\Administrator\Desktop\2017-9-1\apk.conf C:\Users\Administrator\Desktop\2017-9-1\數據采集導入質量統計_2017-09-01.docx C:\Users\Administrator\Desktop\2017-9-1\test1\2017-9-1.txt C:\Users\Administrator\Desktop\2017-9-1\test2\2017-9-1.txt
12、一些表現形式參數
os模塊中還定義了一組文件、路徑在不同操作系統中的表現形式參數。如下:
os.sep # '\\' os.extsep # '.' os.pathsep # ';' os.linesep # '\r\n'
13、獲取在進程的控制終端上登錄的用戶的名稱: os.getlogin() (即此時pc登錄的用戶名)
參數:不需要參數
返回類型:此方法返回一個字符串,該字符串表示在進程的控制終端上登錄的用戶的名稱。
示例:
# Python program to explain os.getlogin() method # importing os module import os # Get the name of the user # logged in on the controlling # terminal of the process. user = os.getlogin() # Print the name of the user # logged in on the controlling # terminal of the process. print(user)
運行結果:
舉例
在自動化測試過程中,常常需要發送郵件,將最新的測試報告文檔發送給相關人員查看,所以就需要查找最新文件的功能。
舉例:查找文件夾下最新的文件。
代碼如下:
import os def new_file(test_dir): #列舉test_dir目錄下的所有文件(名),結果以列表形式返回。 lists=os.listdir(test_dir) #sort按key的關鍵字進行升序排序,lambda的入參fn為lists列表的元素,獲取文件的最后修改時間,所以最終以文件時間從小到大排序 #最后對lists元素,按文件修改時間大小從小到大排序。 lists.sort(key=lambda fn:os.path.getmtime(test_dir+'\\'+fn)) #獲取最新文件的絕對路徑,列表中最后一個值,文件夾+文件名 file_path=os.path.join(test_dir,lists[-1]) return file_path #返回D:\pythontest\ostest下面最新的文件 print new_file('D:\\system files\\workspace\\selenium\\email126pro\\email126\\report')
運行結果:
總結
# python--函數 os.sep :主要用於系統路徑中的分隔符 # Windows系統通過是“\\”,Linux類系統如Ubuntu的分隔符是“/”,而蘋果Mac OS系統中是“:” # 常用的os模塊命令: # 1、os.name——name顧名思義就是'名字',這里的名字是指操作系統的名字,主要作用是判斷目前正在使用的平台,並給出操作系統的名字,如Windows 返回 'nt'; Linux 返回'posix'。注意該命令不帶括號。 # 2、os.getcwd()——全稱應該是'get current work directory',獲取當前工作的目錄 # 3、os.listdir(path)——列出path目錄下所有的文件和目錄名。Path參數可以省略。 # 4、os.remove(path)——刪除path指定的文件,該參數不能省略。 # 5、os.rmdir(path)——刪除path指定的目錄,該參數不能省略。 # 6、os.mkdir(path)——創建path指定的目錄,該參數不能省略。 # 7、os.unlink() 方法用於刪除文件,如果文件是一個目錄則返回一個錯誤 # os.remove() #刪除文件 # os.rename() #重命名文件 # os.walk() #生成目錄樹下的所有文件名 # os.chdir() #改變目錄 # os.mkdir/makedirs() #創建目錄/多層目錄 # os.rmdir/removedirs #刪除目錄/多層目錄 # os.listdir() #列出指定目錄的文件 # os.getcwd() #取得當前工作目錄 # os.chmod() #改變目錄權限 # os.path.basename() #去掉目錄路徑,返回文件名 # os.path.dirname() #去掉文件名,返回目錄路徑 # os.path.join() #將分離的各部分組合成一個路徑名 # os.path.split() #返回(dirname(),basename())元組 # os.path.splitext() #返回filename,extension)元組 # os.path.getatime\ctime\mtime #分別返回最近訪問、創建、修改時間 # os.path.getsize() #返回文件大小 # os.path.exists() #是否存在 # os.path.isabs() #是否為絕對路徑 # os.path.isdir() #是否為目錄 # os.path.isfile() #是否為文件 # os.system('command') 會執行括號中的命令,如果命令成功執行,這條語句返回0,否則返回1
拓展:os.listdir()與os.walk()兩種方式獲取文件路徑與文件目錄下所有子目錄和文件的區別
實例1:在一個目錄下面只有文件時可以使用 os.listdir() 函數
test_file文件夾中包含三個文件:
test_file:
test1.txt
test2.txt
test3.txt
獲取該目錄下的每個文件的絕對路徑:
import os path = r'C:\Users\XXN\Desktop\test_file' for each_file in os.listdir(path): print(os.path.join(path,each_file))
運行結果:
C:\Users\XXN\Desktop\test_file\test1.txt
C:\Users\XXN\Desktop\test_file\test2.txt
C:\Users\XXN\Desktop\test_file\test3.txt
實例2:當一個目錄下面既有文件又有目錄(文件夾),可使用 os.walk() 函數讀取里面所有文件
test_file中既包含文件也包含文件夾:
Test_file:
file1:
test1.txt
test2.txt
test3.txt
file2:
test1.txt
test2.txt
test3.txt
test1.txt
test2.txt
test3.txt
代碼如下:
import os path = r'C:\Users\XXN\Desktop\test_file' for parent,dirnames,filenames in os.walk(path): print(parent,dirnames,filenames)
運行結果:
C:\Users\XXN\Desktop\test_file ['file1', 'file2'] ['test1.txt', 'test2.txt', 'test3.txt'] C:\Users\XXN\Desktop\test_file\file1 [] ['test1.txt', 'test2.txt', 'test3.txt'] C:\Users\XXN\Desktop\test_file\file2 [] ['test1.txt', 'test2.txt', 'test3.txt']
解析:
- parent:列出了目錄路徑下面所有存在的目錄的名稱
- dirnames:文件夾名
- filenames:列出了目錄路徑下面所有文件的名稱
獲得給定路徑下所有的文件路徑:
import os path = r'C:\Users\XXN\Desktop\test_file' for parent,dirnames,filenames in os.walk(path): for filename in filenames: print(os.path.join(parent,filename))
獲取每個文件的絕對路徑