Python os模組中的isfile()和isdir()函數均返回false問題解決方案

來源:互聯網
上載者:User
今天在寫一個linux下自動備份指定目錄下的所有目錄的指令碼時,遇到了一個問題,由於我是需要備份目錄,所以,需要判斷掃描的檔案是否為目錄,當我用os.path.isdir()來判斷的時候,發現所有檔案均返回false,剛開始以為是系統相容性問題,進一步測試,發現用os.path.isfile(),這些檔案還是返回false,這肯定就是程式寫的有問題了,代碼如下:

#!/usr/bin/env python# a python script to auto backup a directory's file by Hitoimport osDirectory=raw_input("Please enter directory you want to backup:")  dirs=os.listdir(Directory)for filename in dirs:  if os.path.isdir(filename):    os.system("tar czvf "+filename+".tar.gz "+filename)

經過仔細排查,在上面的for/in迴圈中,filename實際上只是一個檔案名稱。測試發現,當我使用os.path.isdir(目錄的絕對路徑)的時候,返回的才是true,也就是說,python的isdir()並不像php的is_dir()那樣,可以使用當前工作目錄的相對路徑,那麼這裡怎麼樣去改進這個備份檔案呢?幸好python提供了一個os.path.join()函數,自動來把需要的路徑加到一塊,而不用擔心手動把路徑字串串連起來時,產生多餘的”/”的問題,那麼這個備份指令碼可以這樣寫:

#!/usr/bin/env python# a python script to auto backup a directory's file by Hitoimport osDirectory=raw_input("Please enter directory you want to backup:")  dirs=os.listdir(Directory)for filename in dirs:  fulldirfile=os.path.join(Directory,filename)  if os.path.isdir(fulldirfile):    os.system("tar czvf "+fulldirfile+".tar.gz "+fulldirfile)
  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.