作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在寻找一种 pythonic 方式来创建和写入文件(如果打开文件成功),否则返回错误(例如,权限被拒绝)。
我在这里阅读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 单行或双行能够实现这一目标?
最佳答案
我会做这样的事情:
try:
with open('filename.ext', 'w+') as f:
f.write("Hello world!")
except IOError as e:
# print("Couldn't open or write to file (%s)." % e) # python 2
print(f"Couldn't open or write to file ({e})") # py3 f-strings
根据评论进行编辑,感谢您的输入!
2022-03 为 f 弦编辑
关于打开成功的话pythonic的写法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35975921/
我是一名优秀的程序员,十分优秀!