打开成功的话pythonic的写法

标签 python

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

相关文章:

python - 获取用户是否被登录用户关注,不起作用

python - 为循环编写 python 为 while?

python - POX - 安装一条规则,当某个数据包与 ofp_match 匹配时发送一个虚拟数据包

python - 忽略python中的反斜杠字符

python - 类型错误 : __init__() got an unexpected keyword argument 'name' when loading a model with Custom Layer

python - 复选框检测opencv

python - 让 pandas.read_csv() 忽略 csv 文件开头的垃圾?

python - 在烛台图上绘制移动平均线

python - 在 Python Selenium WebDriver 中按属性查找元素

python - 计算嵌套列表中的字符串