1 回答

TA贡献1934条经验 获得超2个赞
你可以继续前进——但你不应该。此代码不可读。相反,您应该反转 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
这是以这种方式“反转”的问题中的一些代码:
#!/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
添加回答
举报