python - Python Open() gives "invalid argument" error if file already exists
问题描述
My python code is behaving weird and I don't know why:
with open("test.txt", "w") as f:
f.write("this is a test")
with open("test.txt", 'w') as f2:
f2.write("this is also a test")
test.txt
is created and "this is a test"
is written to it. But the second statement gives an error:
Traceback (most recent call last):
File "example.py", line 6, in <module>
with open("test.txt", 'w') as f2:
OSError: [Errno 22] Invalid argument: 'test.txt'
To my knowledge, 'w'
would overwrite this file.
Does anyone have any idea why this is happening?
EDIT: I tried the code above on a different machine. Here it has the desired effect of overwriting the code. The question thus changes: What causes python to change its behaviour like this?
解决方案
我重新安装了python。这解决了问题。示例中的代码运行良好。
“w”替换文件的内容。 https://docs.python.org/3/library/functions.html#open
推荐阅读
- c# - 如何在 WPF 中以编程方式清除所有项目的列表框?
- php - 通过 php 提供大文件,不在 public_html 中
- c# - “参数化查询需要一个未提供的参数”错误
- javascript - 使用当前 vue 组件的方法作为默认 prop 值
- ruby - 使用 will_paginate 分页没有活动记录只显示第一页的值,下一页完全为空
- python - 如何使用交互方法构建模块
- r - 有人可以协助在 R 中使用“httr”包进行 API 调用吗?
- python - 如何在 matplotlib 中将列指定为轴并绘制条形图?
- azure - 如何通过 FQDN 寻址 VNET 中的其他 VM?
- java - 如何将http响应放入Set