[英]Python Open() gives "invalid argument" error if file already exists
我的 python 代码表现得很奇怪,我不知道为什么:
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
被创建并且"this is a test"
被写入其中。 但是第二个语句给出了错误:
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'
据我所知, 'w'
会覆盖这个文件。 有谁知道为什么会这样?
编辑:我在另一台机器上尝试了上面的代码。 在这里它具有覆盖代码的预期效果。 问题因此而改变:是什么导致 python 像这样改变它的行为?
我重新安装了python。 这解决了问题。 示例中的代码运行良好。
“w”替换文件的内容。 https://docs.python.org/3/library/functions.html#open
用这个:
f = open("test.txt", "w")
f.write("this is a test")
f.close()
f2 = open("test.txt", "w")
f2.write("this is also a test")
f2.close()
我认为问题是你试图在不关闭它的情况下使用同一文件的另一个实例,据说写这个也应该有效:
f2.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.