写程式经常需要检查一个档案或目录是否存在, 一般上 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.