1. 程式人生 > 實用技巧 >os模組 -os_shutile模組 - os路徑模組

os模組 -os_shutile模組 - os路徑模組

一 os模組 對系統進行操作

引入 import os

1. system() 在python中執行系統命令

# os.system("touch 1.txt")
# os.system("ipconfig")
# os.system("ifconfig")
View Code

2. popen() 執行系統命令返回物件,通過read方法讀出字串

obj = os.popen('ifconfig')
res = obj.read()
print(res)
View Code

3. listdir() 獲取指定資料夾中所有內容的名稱列表

lst = os.listdir('.
') print(lst)
View Code

4. getcwd() 獲取當前檔案所在的預設路徑

# 路徑
res = os.getcwd()
print(res)

# 路徑 + 檔案
print(__file__)
View Code

5. chdir() 修改當前檔案工作的預設路徑

如果在這裡面寫上
os.system('') 就相當於在這裡面做操作
View Code

6. environ 獲取或修改環境變數

print(os.environ)
print(os.environ["PATH"])
os.environ["PATH"] += ":/home/wangwen/mysoft
" os.system("wangwen")
View Code

7. name 獲取系統標識

linux.mac-> posix  windows-> \
print(os.name)
View Code

8. sep 獲取路徑分割符號

linux,mac -> /       window-> \
res = 'wangwen'+os.sep + 'notepad'
print(repr(res))
View Code

9. linesep 獲取系統的換行符號

linux,mac -> \n    window->\r\n 或 \n
print
(repr(os.linesep))
View Code

二 .os模組具有 新建/刪除/

引入 import os

1. os.mknod 建立檔案

os.mknod('lianxi.py')
View Code

2. os.remove 刪除檔案

os.remove('lianxi.py')
View Code

3.os.mkdir 建立目錄(資料夾)

os.mkdir("abc_ww")
View Code

4.os.rmdir 刪除目錄(資料夾)

os.rmdir("abc_ww")
View Code

5. os.rename 對檔案,目錄重新命名

os.rename("lianxi1","lianxi2")
View Code

6.os.makedirs 遞迴建立資料夾

os.makedirs("a/b/c/d/e/f/g")
View Code

7.os.removedirs 遞迴刪除資料夾(空資料夾)

os.removedirs("a/b/c/d/e/f/g")
View Code

三 . shutil模組 複製/移動

引入 import shutil

1. 複製內容

fp1 = open('lianxi2',mode='r+',encoding='utf-8')
fp2 = open('lainxi1.txt',mode='w',encoding='utf-8')
shutil.copyfileobj(fp1,fp2)
View Code

2 copymode(src,dst) #單純的僅複製檔案許可權 , 不包括內容

"""複製許可權時,必須檔案存在"""

shutil.copymode("ceshi3.py","lianxi2")
View Code

3. copystat(src,dst) #複製所有狀態資訊,包括許可權,組,使用者,修改時間等,不包括內容

shutil.copystat("lianxi2","ceshi4.py")
View Code

4. copy 和 copy2

#copy(src,dst)       #複製檔案許可權和內容
# shutil.copy("lianxi2","ceshi5.py")

#copy2(src,dst)      #複製檔案許可權和內容,還包括許可權,組,使用者,時間等
# shutil.copy2("lianxi2","ceshi6.py")
View Code

5.遞迴拷貝/刪除

#copytree(src,dst)   #拷貝資料夾裡所有內容(遞迴拷貝)
# shutil.copytree("ceshi777","ceshi666")

#rmtree(path)        #刪除當前資料夾及其中所有內容(遞迴刪除)
# shutil.rmtree("ceshi777")
View Code

6.剪下

#move(path1,paht2)   #移動檔案或者資料夾
# shutil.move("ceshi1.txt","pycharm-community-2020.1.3/ceshi2.ttt")
View Code

四. os路徑模組 -os.path

引入 import os.time

1.basename() 返回檔名部分

res = os.path.basename(pathvar)
print(res)
View Code

2. dirname() 返回路徑部分

res = os.path.dirname(pathvar)
print(res)
View Code

3 . split() 將路徑拆分成單獨的檔案部分和路徑部分 組合成一個元組

tup = os.path.split(pathvar)
print(tup)
View Code

4. join() 將多個路徑和檔案組成新的路徑 可以自動通過不同的系統加不同的斜槓 linux / windows\

path1 = "home"
path2 = "wangwen"
path3 = "mysoft"
# 方法一
pathvar = path1 + os.sep + path2 + os.sep + path3
print(pathvar)
# 方法二(推薦)
pathvar = os.path.join(path1,path2,path3)
print(pathvar)
View Code

5 .getsize() 獲取檔案的大小 ***

"""getsize只能獲取檔案大小,不能獲取資料夾的大小"""

print(os.getcwd())
pathvar = os.path.join(os.getcwd(),"1.txt") # /mnt/hgfs/python33_gx/day17/1.txt
print(pathvar)
res = os.path.getsize(pathvar)
print(res)
View Code

7. isdir() 檢測路徑是否是一個資料夾 ***

pathvar = os.path.join(os.getcwd(),"1.txt") # /mnt/hgfs/python33_gx/day17/1.txt
res = os.path.isdir(pathvar)
print(res)
View Code

8. isfile() 檢測路徑是否是一個檔案 ***

res = os.path.isfile(pathvar)
print(res)
View Code

9. islink() 檢測路徑數否是一個連結 **

res = os.path.islink("/home/wangwen/ceshi03/ceshi01")
print(res)
View Code

10. getctime() [windows]檔案的建立時間,[linux]許可權的改動時間(返回時間戳) **

res = os.path.getctime("ceshi2.py") 
print(res) 
View Code

11getmtime() 獲取檔案最後一次修改時間(返回時間戳) **

res = os.path.getmtime("ceshi2.py") 
print(res) 
View Code

12 getatime() 獲取檔案最後一次訪問時間(返回時間戳) **

res = os.path.getatime("ceshi2.py") 
print(res) 
View Code

13 exists() 檢測指定的路徑是否存在 ***

res = os.path.exists("ceshi4.py")
print(res)
View Code

14.isabs() 檢測一個路徑是否是絕對路徑 ***

pathvar = "."
res = os.path.isabs(pathvar)
print(res)
View Code

15 .abspath() 將相對路徑轉化為絕對路徑 ***

res = os.path.abspath(pathvar)
print(res)
View Code

五 . 小練習 計算檔案的大小

def getallsize(pathvar):
    size = 0
    lst = os.listdir(pathvar)
    for i in lst:
        pathnew = os.path.join(pathvar,i)
        if os.path.isdir(pathnew):
            size += getallsize(pathnew)
        elif os.path.isfile(pathnew)
            size += os.path.getsize(pathnew)

    return size

res = getallsize(pathvar)
print(res)
View Code

六 . tarfile 模組

import tarfile

1.建立tar包

# 1.建立壓縮包
tf = tarfile.open("ceshi1210.tar","w",encoding="utf-8")
# 2.寫入檔案
tf.add("/bin/cat","cat")
tf.add("/bin/chacl","chacl")
tf.add("/bin/cp","tmp/cp")
tf.add("/aaabbb","aaabbb") #可直接壓縮資料夾
# 3.關閉檔案
tf.close() # 225,280 

2.建立.tar.gz包

tf = tarfile.open("ceshi1210.tar.gz","w:gz",encoding="utf-8")
tf.add("/bin/cat","cat")
tf.add("/bin/chacl","chacl")
tf.add("/bin/cp","tmp/cp")
tf.add("/aaabbb","aaabbb")
tf.close() # 96,797

3.建立.tar.bz2包

tf = tarfile.open("ceshi1210.tar.bz2","w:bz2",encoding="utf-8")
tf.add("/bin/cat","cat")
tf.add("/bin/chacl","chacl")
tf.add("/bin/cp","tmp/cp")
tf.add("/aaabbb","aaabbb")
tf.close() # 84078

4 .解壓檔案

tf = tarfile.open("ceshi1210.tar.bz2","r",encoding="utf-8")
# 解壓所有
# tf.extractall("ceshi1210")
# 解壓單個(落腳在檔案身上)
tf.extract("aaabbb/1.py","ceshi1210_1")
tf.close()

5 .檢視檔案 (使用with語法)

with tarfile.open("ceshi1210.tar.bz2","r",encoding="utf-8") as tf:
    lst = tf.getnames()
    print(lst)

6 . 追加檔案

"""無法對已經壓縮過的壓縮包做內容的追加;"""

# with tarfile.open("ceshi1210.tar","a",encoding="utf-8") as tf:
    # tf.add("/bin/mv","mv") # success 

# with tarfile.open("ceshi1210.tar.bz2","a",encoding="utf-8") as tf:
    # tf.add("/bin/mv","mv") # error

7.解決辦法

"""
1.先解壓
2.將檔案追加到該資料夾中
3.在重新過濾打包即可
"""

# 1.先解壓檔案
with tarfile.open(pathvar1,"r",encoding="utf-8") as tf:
    tf.extractall("ceshi1210_2")

# 2.將檔案追加到該資料夾中
shutil.copy("/bin/nano",pathvar2)

# 3.在重新過濾打包即可
"""過濾掉cat,剩下的資料打包"""
lst = os.listdir(pathvar2)
print(lst) # ['aaabbb', 'cat', 'chacl', 'nano', 'tmp']


with tarfile.open(pathvar1,"w:bz2",encoding="utf-8") as tf:
    for i in lst:
        if i != "cat":
            # 拼接好完整絕對路徑
            pathvar = os.path.join(pathvar2,i)
            # 新增到壓縮包中
            tf.add(pathvar,i)