gpt4 book ai didi

打开成功的话pythonic的写法

转载 作者:太空狗 更新时间:2023-10-29 20:36:30 28 4
gpt4 key购买 nike

我正在寻找一种 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com