我正在寻找使用Python的方法来创建并写入文件,如果成功打开文件则进行操作,否则返回错误(例如权限被拒绝)。
我在这里阅读了这篇文章What's the pythonic way of conditional variable initialization?。虽然我不确定这种方法是否可行,因为我已经尝试过测试它。
os.write(fd,String) if (fd = os.open(str("/var/www/file.js"),os.O_RDWR)) else return HttpResponse("error on write")
它应该只是一行代码。
当我执行上述操作时,我会遇到如下的语法错误:
os.write(fd,String) if (fd = os.open(str("/var/www/file.js"),os.O_RDWR)) else return HttpResponse("error on write")
^
SyntaxError: invalid syntax `
有没有更加pythonic的一行或两行代码可以实现这个目的?
value1 if condition else value2
,而不是statement1 if condition else statement2
。返回语句不是一个值,因此不能在三元操作符中使用。 - khelwoodwith
语句。 - PM 2Ringtry: with open(...) except: print("跳过并失败。无怨无悔!")
,除非你只想寻找三元运算符的解决方案。 - jDo