首页 > 解决方案 > 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

解决方案


我重新安装了python。这解决了问题。示例中的代码运行良好。

“w”替换文件的内容。 https://docs.python.org/3/library/functions.html#open


推荐阅读