1 回答
TA貢獻(xiàn)1934條經(jīng)驗(yàn) 獲得超2個贊
你可以繼續(xù)前進(jìn)——但你不應(yīng)該。此代碼不可讀。相反,您應(yīng)該反轉(zhuǎn) if 檢查。例如,如果您的代碼僅在路徑是文件時才有效,則不是:
if os.path.isfile('/path/to/file'):
# rest of code
你可以這樣做:
if not os.path.isfile('/path/to/file'):
# error handling, reporting, change of control etc.
# rest of code
這是以這種方式“反轉(zhuǎn)”的問題中的一些代碼:
#!/usr/bin/python
import os
import sys
if not os.path.isfile('/tmp/EXAMPLE.txt'):
print('File does not exist')
sys.exit(1)
if os.path.getsize('/tmp/EXAMPLE.txt') != 0:
print('File has data already')
sys.exit(1)
if os.access('/tmp/EXAMPLE.txt', os.W_OK) == False:
print('File does not have write permissions')
sys.exit(1)
# rest of the code
添加回答
舉報(bào)
