Python3 - os模塊和shutil模塊常用方法及實例


os 模塊

  1. os.getcwd() 函數
    getcwd = get current working directory得到當前工作目錄,即當前Python腳本工作的目錄路徑

    >>> os.getcwd()
    '/Users/Documents'
    
  2. os.name
    字符串指示你正在使用的平台。比如對於Windows,它是'nt',而對於Linux/Unix用戶,它是 'posix'

    >>> os.name
    'posix'
    
  3. os.listdir(path)
    返回給定目錄path下所有內容列表(也包含所有隱藏的文件夾和文件)

     >>> os.listdir('/Users/virgil/Documents/GitHub/PySpider')
     ['.DS_Store', '.git', '.vscode', 'README.md', 'test.py']
    
  4. os.remove(path)
    用來刪除一個文件,path必須是文件名,如果是文件夾會報錯PermissionError: [Errno 1] Operation not permitted:

    >>> os.remove('/Users/Documents/GitHub/testtttt/README.MD')
    
  5. os.removedirs(path)
    遞歸刪除目錄,只能刪除目錄下沒有內容的文件夾,否則報錯OSError: [Errno 66] Directory not empty:

    >>> os.removedirs('/Users/Documents/GitHub/testtttt')
    
  6. os.curdir 返回當前目錄 ('.')

    >>> os.curdir
    '.'
    
  7. os.mkdir(path) 創建一個目錄

    >>> os.mkdir('testaaaaaaaa') #在當前工作目錄os.getcwd()下創建文件夾'testaaaaaaaa'
    >>> os.mkdir('testaaaaaaaa/test/test1')    #不存在test目錄,報錯FileNotFoundError: [Errno 2] No such file or directory: 'testaaaaaaaa/test/test1'
    
  8. os.makedirs(path) 遞歸的創建目錄

    >>> os.makedirs('test/test1/test2') #新建test目錄,在test下創建test1目錄,在test1下創建test2目錄
    
  9. os.chdir(dirname) 改變工作目錄到dirname

    >>> os.chdir('/Users/Documents/GitHub')
    >>> os.getcwd()
    '/Users/Documents/GitHub'
    
  10. os.system(command) 函數用來運行shell命令

  11. os.path.split(path) 函數返回一個路徑的目錄名和文件名

    >>> os.path.split('/Users/Documents/GitHub/testtttt')
    ('/Users/Documents/GitHub', 'testtttt')
    >>> os.path.split('/Users/Documents/GitHub/testtttt/README.MD')
    ('/Users/Documents/GitHub/testtttt', 'README.MD')
    
  12. os.path.isfile(path) 和os.path.isdir(path)函數分別檢驗給出的路徑是一個文件還是目錄

  13. os.path.exists(path) 函數用來檢驗給出的路徑是否真地存在

  14. os.curdir 返回當前目錄 ('.')

15.os.chdir(dirname) 改變工作目錄到dirname
>>> os.getcwd() '/Users/Documents' >>> os.chdir('/Users/virgil/Documents/Apple/GitHub') >>> os.getcwd() '/Users/Documents/GitHub'
16. os.path.getsize(name) 獲得文件大小,如果name是目錄返回0L
17. os.path.abspath(name) 獲得絕對路徑
18. os.path.normpath(path) 規范path字符串形式
19. os.path.splitext() 分離文件名與擴展名
>>> os.path.split('/Users/virgil/Documents/Apple/GitHub/testtttt') ('/Users/Documents/GitHub', 'testtttt') >>> os.path.split('/Users/Documents/GitHub/testtttt/README.MD') ('/Users/Documents/GitHub/testtttt', 'README.MD')
20. os.path.join(path,name) 連接目錄與文件名或目錄
21. os.path.basename(path) 返回文件名
22. os.path.dirname(path) 返回文件路徑

shutil模塊:It is a utility module which can be used to accomplish tasks, such as: copying, moving, or removing directory trees
參考:https://www.pythonforbeginners.com/os/python-the-shutil-module

  1. shutil.copy(src,dest)
    將目標文件拷貝到目標路徑,目標路徑必須存在。
    如果源文件已經存在目標路徑,直接覆蓋。
    拷貝到目標路徑后,文件的狀態(連接時間和更新時間)都會被更新,文件名、文件內容和文件的權限都不變。

    import shutil
    import os
    source = os.listdir("/tmp/")
    destination = "/tmp/newfolder/"
    for files in source:
        if files.endswith(".txt"):
            shutil.copy(files,destination)
    
  2. shutil.copyfile(src,dest)
    拷貝文件,src和dest是帶文件名的路徑,如/Users/Documents/test.txt'
    源文件必須存在,拷貝的文件內容不變,可以改變目標文件名,xyz.txt是test.txt的復制,內容一樣,名字改了

    import shutil
    shutil.copyfile('/Users/Documents/test.txt','/Users/Documents/GitHub/xyz.txt')
    
  3. shutil.move(src,dest)
    遞歸地將文件或目錄(src)移動到另一個位置(dst)。目標目錄應該不存在。
    如果目標是一個目錄或指向一個目錄的符號鏈接,那么src將被移動到該目錄中。
    下面的例子:把文件以.txt結尾的文件移動到目標路徑。

    import shutil
    import os
    source = os.listdir("/tmp/")
    destination = "/tmp/newfolder/"
    for files in source:
        if files.endswith(".txt"):
            shutil.move(files,destination)
    
  4. shutil.copytree(src , dest)
    遞歸地將src下的整個目錄樹復制到dest。
    src必須存在,dest必須不存在。

    import shutil
    import os
    os.getcwd()    #得到當前工作目錄
    SOURCE = "test"    #文件夾test    
    BACKUP = "samples-bak"
    # create a backup directory
    shutil.copytree(SOURCE, BACKUP)
    print(os.listdir(BACKUP))    #以list形式列出backup目錄下所有文件
    
  5. shutil.rmtree(path)
    遞歸地刪除目錄和目錄下的所有內容
    例子:刪除文件系統中目錄為“three”及其下面的所有內容

    import shutil
    shutil.rmtree('one/two/three')
    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM