[英]How to check that a path is an existing regular file and not a directory?
一個腳本用於在團隊之間交換文件信息。 它用作:
$ share.py -p /path/to/file.txt
參數檢查可確保/path/to/file.txt
存在並且具有正確的權限:
#[...]
# ensure that file exists and is readable
if not os.access(options.path, os.F_OK):
raise MyError('the file does not exist')
# ensure that path is absolute
if not os.path.isabs(options.path):
raise MyError('I need absolute path')
# ensure that file has read permissions for others
info = os.stat(options.path)
last_bit = oct(info.st_mode)[-1]
if not last_bit in ['4', '5', '6', '7']:
raise MyError('others cannot read the file: change permission')
問題是一位用戶發送了:
$ share.py -p /路徑/到/
並且程序沒有失敗,應該有的失敗。 回顧過去,我應該看到這種情況的到來,但我沒有。
如何添加測試以確保路徑是帶有或不帶有擴展名的常規文件(我不能簡單地處理name字符串 )?
import os.path
os.path.isfile(filename)
os.path.exists(path) and not os.path.isdir(path)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.