【问题标题】:How do i solve "FileNotFoundError: [Errno 2] No such file or directory:" in Python whilst using Visual Studio Code?如何在使用 Visual Studio Code 时在 Python 中解决“FileNotFoundError:[Errno 2] No such file or directory:”?
【发布时间】:2020-11-08 22:47:21
【问题描述】:

我刚刚开始学习 Python,我观看了这个视频教程 - https://www.youtube.com/watch?v=rioXu6EBN0s

当我尝试使用视频中的方法创建自己的 .hmtl 文件时,出现此错误 -

FileNotFoundError: [Errno 2] No such file or directory:

这是我在 Visual Studio 中输入的——

my_variable = "<html><body><p>This is a paragraph.</p><p>This is another paragraph.</p></body></html>"

my_html_file = open("C:\Users\Liam\Documents\Coding\My Files\Python\My Tests/my_html_file.html" "w")

my_html_file.write(my_variable)

我试过改成

/Users/Liam.Documents/Coding/My Files/Python/My Tests/
/my_html_file.html

但它没有奏效,任何建议将不胜感激。

利亚姆

【问题讨论】:

  • 目录是否存在?
  • 参数之间需要逗号,否则 Python 会连接字符串。输入, "w") 而不仅仅是"w")。它将寻找.htmlw 文件并尝试以“读取”模式打开它。
  • 亲爱的彼得,谢谢你,这就是问题所在,我不敢相信我错过了。

标签: python visual-studio


【解决方案1】:

当您需要调试时,您需要更改文件的路径以在调试模式下打开它,只需:

  1. 去探险家
  2. 右键文件,点击复制相对路径
  3. 打开该路径

我还看到你把这个放在你的代码中:

my_html_file = open("C:\Users\Liam\Documents\Coding\My Files\Python\My Tests/my_html_file.html" "w")

你在w之前少了一个昏迷,应该是这样的:

my_html_file = open("C:\Users\Liam\Documents\Coding\My Files\Python\My Tests/my_html_file.html","w")

编辑:大声笑,现在我看到其他人通过回复来回答您的问题,无论如何,这也应该对其他人有所帮助!至少……

【讨论】:

  • 这真的很有帮助。谢谢。
【解决方案2】:

原因是文件名和用于打开文件的模式之间缺少逗号。因此,解释器正在尝试读取文件,如果您请求的文件不存在,则会导致错误。

【讨论】:

    猜你喜欢
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多