假设我有一些用python 2.7编写的代码,该代码依赖于一个if语句为true,然后使用另一个if条件,另一个取决于两个最终条件是否为true,我可以在我的代码中永远永久这样做吗?限制?而且有什么我可以做得更好吗?
#!/usr/bin/python
import os
if os.path.isfile('/tmp/EXAMPLE.txt'):
if os.path.getsize('/tmp/EXAMPLE.txt') == 0:
if os.access('/tmp/EXAMPLE.txt', os.W_OK) == True:
DATA = open('/tmp/EXAMPLE.txt', 'w')
if DATA.mode == 'w':
DATA.write('DATA')
DATA.close()
DATA = open('/tmp/EXAMPLE.txt', 'r')
if DATA.mode == 'r':
if 'DATA' in DATA.read():
print 'File size is no longer zero'
else:
print 'Data failed to write'
else:
print 'File could not be read from'
else:
print 'File could not written to'
else:
print 'File does not have write permissions'
else:
print 'File has data already'
else:
print 'File does not exist'
您可以继续前进-但您不应该这样做。该代码不可读。相反,您应该反转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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句