【问题标题】:Errno 17 File exists: 'example.bat'Errno 17 文件存在:'example.bat'
【发布时间】:2020-10-13 01:05:22
【问题描述】:
with open('example.bat', 'x') as f:
    for line in f:
     print(line, end='')

我试图让我的代码打开一个 .bat 文件,但得到 [Errno 17] 文件存在:'filename.bat'。谁能帮我解决一下

【问题讨论】:

  • 使用'x' 模式打开文件进行写入,它要求文件不存在。但看起来您实际上是在尝试读取文件,而不是写入文件。 (如果你不知道'x' 模式是做什么的,你为什么要使用它?)

标签: python python-3.x error-handling


【解决方案1】:

尝试使用 r+ 打开文件,因为您想读取它,如果文件不存在,它将创建文件(如果不存在,x 打开用于写入)或使用 rw+ 进行读/写:

 with open('example.bat', 'r+') as f:
    for line in f:
     print(line, end='')

【讨论】:

  • 谢谢,但现在 .bat 只是在终端中用 vs 代码写出它的命令我如何让它真正让它运行 .bat 文件。
猜你喜欢
  • 2015-03-14
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 2013-06-06
  • 2021-09-27
  • 1970-01-01
  • 2012-08-25
  • 1970-01-01
相关资源
最近更新 更多