收集了一些關于OS庫的用法,整理歸納一下,方便使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
import os # 系統操作 print (os.sep) # 獲取當前系統的路徑分隔符 print (os.name) # 獲取當前使用的工作平臺 print (os.getenv( 'PATH' )) # 獲取名為 PATH 的環境變量 print (os.getcwd()) # 獲取當前的路徑 print (os.environ[ 'PATH' ]) # 可以返回環境相關的信息 不傳參時,以字典的方式返回所有環境變量 # 調用系統命令 os.system(command) # 將linux命令傳入這里,就可以執行 Execute the command in a subshell. # 目錄操作 - 增刪改查 dir = "/opt/" listdir_opt = os.listdir( dir ) # 返回指定目錄下的所有文件何目錄名 print (listdir_opt) os.mkdir( "/opt/os-make/" ) # 創建一個目錄,只創建一個目錄文件 os.mknod( "/root/python-test.txt" ) # 創建一個文件 os.rmdir( "/opt/ooo/" ) # 刪除一個空目錄,若目錄中有文件則無法刪除 os.remove( "/tmp/test.txt" ) # 用于刪除文件,若是目錄,則拋出 IsDirectoryError 異常 os.makedirs( "/opt/os-make-again/os-make-again-again" ) # 可以生成多層遞歸目錄,如果目錄全部存在,則創建目錄失敗 os.removedirs() # 從最下級目錄開始,逐級刪除指定路徑,遇到非空目錄即停止 os.chdir( "/tmp/" ) # 改變當前目錄,到指定目錄 os.rename( "/opt/ooo/" , "/opt/AAA/" ) # 重命名目錄名或者文件名。重命名后的文件已存在,則重命名失敗。 """ os.rename()函數的作用是將文件或路徑重命名,一般調用格式為os.rename(src, dst),即將src指向的文件或路徑重命名為dst指定的名稱。 注意,如果指定的目標路徑在其他目錄下,該函數還可實現文件或路徑的“剪切并粘貼”功能。但無論直接原地重命名還是“剪切粘貼”,中間路徑都必須要存在,否則就會拋出FileNotFoundError異常。如果目標路徑已存在,Windows 下會拋出FileExistsError異常;Linux 下,如果目標路徑為空且用戶權限允許,則會靜默覆蓋原路徑,否則拋出OSError異常, 和上兩個函數一樣,該函數也有對應的遞歸版本os.renames(),能夠創建缺失的中間路徑。 注意,這兩種情況下,如果函數執行成功,都會調用os.removedir()函數來遞歸刪除源路徑的最下級目錄。 """ # 判斷 if os.path.exists( "/root" ): print ( "/root 目錄存在!" ) if os.path.isfile( "/root" ): print ( "/root 文件存在!" ) if os.path.isdir( "/etc" ): print ( "/etc 目錄存在!" ) if os.path.isabs( "/etc" ): print ( "/etc 是絕對路徑!" ) # path模塊 """ os.path中的函數基本上是純粹的字符串操作。換句話說,傳入該模塊函數的參數甚至不需要是一個有效路徑,該模塊也不會試圖訪問這個路徑,而僅僅是按照“路徑”的通用格式對字符串進行處理。 """ path = "/etc/passwd" filename = os.path.basename(path) # 返回文件名,如果是目錄則為空 實際上是傳入路徑最后一個分隔符之后的子字符串,也就是說,如果最下級目錄之后還有一個分隔符,得到的就會是一個空字符串 filedir = os.path.dirname(path) # 返回的是最后一個分隔符前的整個字符串 filesplit = os.path.split(path) # 將傳入路徑以最后一個分隔符為界,分成兩個字符串,并打包成元組的形式返回 """ 類似的 os.path.splitext("ooo.txt") ('ooo', '.txt') """ filesize = os.path.getsize(path) # 獲取文件的大小 相當于 ls -l 單位為bytes fileAbsPath = os.path.abspath(path) # 獲取文件的絕對路徑 filejoin = os.path.join(path, "test.txt" ) # 拼接新的路徑 """ 如果傳入路徑中存在一個“絕對路徑”格式的字符串,且這個字符串不是函數的第一個參數,那么其他在這個參數之前的所有參數都會被丟棄,余下的參數再進行組合。更準確地說,只有最后一個“絕對路徑”及其之后的參數才會體現在返回結果中。 例子如下: os.path.join("just", "do", "/opt/", "it") 結果: /opt/it os.path.join("just", "do", "/opt/", "python", "dot", "/root", "com") 結果:/root/com """ print (filename + "\n" + filedir + "\n" + str (filesize) + "\n" + fileAbsPath + "\n" + filejoin + "\n" ) |
以上模塊和函數的用法已經做了一些說明,理解起來也不難,下面再介紹一個函數os.walk()
1
2
3
4
|
import os for item in os.walk( "/opt/test-walk/" ): print (item) |
程序輸出結果
('/opt/test-walk/', ['a', 'b', 'c'], [])
('/opt/test-walk/a', [], ['a.txt'])
('/opt/test-walk/b', ['b2'], [])
('/opt/test-walk/b/b2', [], ['b.txt'])
('/opt/test-walk/c', [], [])
目錄結構
1
2
3
4
5
6
7
8
9
10
|
[root@open-1 python_scripts]# tree /opt/test-walk/ /opt/test-walk/ ├── a │ └── a.txt ├── b │ └── b2 │ └── b.txt └── c 4 directories, 2 files |
由上面的結果可以大致明白os.walk()函數的作用:這個函數需要傳入一個路徑作為參數,函數的作用是在該路徑為根節點的目錄樹中游走,對樹中的每個目錄生成一個由(dirpath, dirnames, filenames)三項組成的三元組。其中,dirpath是一個指示這個目錄路徑的字符串,dirnames是一個dirpath下子目錄名(除去 . 和 ..)組成的列表,filenames則是由dirpath下所有非目錄的文件名組成的列表。簡單來說,就是把目標路徑下的所有目錄和文件都列出來,結合tree命令的結果,就更好理解這個函數的作用了.
----------------------練習------------------------
在當前目錄新建目錄img, 里面包含多個文件, 文件名各不相同(X4G5.png)
將當前img目錄所有以.png結尾的后綴名改為.jpg
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
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' ) |
-----------------練習-----------------------
利用time.time()方法,我們可以計算兩個時間點之間的時間間隔
但是有些時候我們想要得到/etc/group文件的a/c/m的時間
對應的年月日這些信息
并保存再文件date.txt文件中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import os import time time1 = os.path.getctime( '/etc/shadow' ) #時間戳時間 print (time1) tuple_time = time.localtime(time1) print (tuple_time) year = tuple_time.tm_year month = tuple_time.tm_mon day = tuple_time.tm_mday with open ( 'date.txt' , 'a' ) as f: f.write( '%d %d %d' % (year,month,day)) f.write( '\n' ) |
到此這篇關于Python寫腳本常用模塊OS基礎用法詳解的文章就介紹到這了,更多相關Python 模塊OS使用內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/rookie23rook/article/details/115076748