寫程式經常需要檢查一個檔案或目錄是否存在, 一般上 Scripting Language 都不會太困難, 而 Python 要檢查同樣很方便, 只要用 os.path.isfile() 及 os.path.isdir() 便可以實現。
檢查檔案是否存在
當檔案存在時, os.path.isfile() 會回傳 TRUE, 例如:
|
1 2 3 4 5 6 7 8 9 |
#!/usr/bin/python import os file_path = "/var/www/html/test.html" if ( os.path.isfile(file_path)): print("File exists!") else: print("File not found!") |
不論輸入到 os.path.isfile() 的是檔案還是連結檔, 它也會回傳 TRUE.
檢查目錄是否存在
要檢查目錄是否存在, 跟上面的例子差不多, 只要改用 os.path.isdir() 即可, 例如:
|
1 2 3 4 5 6 7 8 9 |
#!/usr/bin/python import os dir_path = "/var/www/html/test_dir" if ( os.path.isdir(dir_path)): print("Directory exists!") else: print("Directory not found!") |
跟 isfile 一樣, isdir 對連結目錄同樣會回傳 TRUE.
如果只要檢查輸入的路徑是否存在, 不論是檔案或目錄都會回傳 TRUE, 這樣可以用 os.path.exists():
|
1 2 3 4 5 6 7 8 9 |
#!/usr/bin/python import os fp_path = "/var/www/html/test_dir" if ( os.path.exists(fp_path)): print("Path exists!") else: print("Path not found!") |
輸入到 fp_path 變數的路徑, 不論是檔案或目錄, 只要存在, os.path.exists() 也會回傳 TRUE.