python os.fdopen(os.open()) 不能用来写?

标签 python

这个问题与 Write file with specific permissions in Python 的答案有关用于打开具有特定权限的写入文件(在 python 中)。

答案中的代码如下所示:

with os.fdopen(os.open('foo', os.O_APPEND | os.O_CREAT, 0o644)) as out:
  out.write("hello\n")

2.7.1 中的这段代码(我公司没有安装 2.7.3)产生:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IOError: File not open for writing

os.fdopen 有自己的模式参数,但设置没有帮助:

>>> with os.fdopen(os.open('foo', os.O_APPEND | os.O_CREAT, 0o644), 'a') as out:
...   out.write("hello\n")
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument

长话短说,我无法弄清楚如何实际写入已通过 os.fdopenos.open 打开的文件。有任何想法吗? 2.7.1 中的已知错误?

提前致谢!

最佳答案

您必须选择 O_RDONLY、O_WRONLY 或 O_RDWR 之一作为 open() 的“基本”模式参数。

您没有明确地这样做,因此假定为 O_RDONLY(在许多系统上为零)。 Python 的 os.fdopen 看到您指定了一个 O_RDONLY O_APPEND,这有点傻。 Python 提示这种组合与您看到的 EINVAL(“无效参数”)错误。

(事实上,如果您 strace(1) 您的脚本 — 我假设这里是 Linux — 我怀疑您会看到没有遇到“自然的” EINVAL。相反,python 执行您的 os.open()/open(2),然后在引发异常之前检查文件描述符上的标志 (F_GETFL)。)

关于python os.fdopen(os.open()) 不能用来写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13257748/

相关文章:

python - Pandas 比较相似的 DataFrames 并获得 Min

python - 匹配多个正则表达式组并删除它们

python - RegEx Python 查找并打印到新文档

python - tensorflow.keras.preprocessing.text.Tokenizer 中的文本编码与旧的 tfds.deprecated.text.TokenTextEncoder 有何不同

Python - 单元格类型 'NoneType' 而值在里面。怎么改造呢?

python - 在 IDLE 中运行 python 脚本时,有没有办法传入命令行参数(args)?

python - Django Form 不从类 HomeForm 渲染 HTML

python - PIL 安装失败缺少 :stdarg. h

python - 有没有办法将 XML 转换为字典和列表?

python - 如何使用PIL(Python Image Library)旋转图片让黑色背景变透明