【问题标题】:Python: File Not Found Error. No such file or directory namedPython:找不到文件错误。没有这样的文件或目录命名
【发布时间】:2021-05-11 09:04:32
【问题描述】:

我必须在我的 slakes.py 文件中读取一个名为“highscore.txt”的简单文件。 两者都位于同一个文件夹中。 但是我知道为什么我找不到文件错误 代码:

with open('highscore.txt', 'r') as f:
    high_score = f.read()

【问题讨论】:

  • 您是否也在同一个文件夹中运行 Python?读取相对路径时,Python 从当前工作目录(不是脚本文件)读取。例如... ``` $ pwd /path/to/my/project $ ls /path/to/my/project ./code $ ls /path/to/my/project/code ./script.py ./highscores .txt $ python ./code/script.py FileNotFoundError [Errno 2] 没有这样的文件或目录:highscores.txt ```

标签: python python-3.x visual-studio-code


【解决方案1】:

这部分代码检查file是否存在。如果不是 - 创建这个空文件并读取这个文件。
我建议使用您的文件的完整路径,例如 /home/user/folde/subfolder/file.txt
希望这对您有所帮助。

from subprocess import call as subprocess_call
from os.path import isfile as file_exist
file = "/path/to/your/file"
if not file_exist(file):
    # create file if exist
    subprocess_call(["touch", file])
    subprocess_call(["chmod", "777", file])
with open(file, "r") as f:
     high_score = f.read()
    

【讨论】:

    【解决方案2】:

    尝试使用名为 csv 的模块 以下代码是读取文件的基本代码:

        import csv
        with open('file directory') as F:
            reader = csc.reader(F)
            for row in reader:
                print (rows)
    

    你可以使用任何变量

    【讨论】:

    • 好的,我会尝试,但你能告诉我为什么 python 会给出错误吗?
    【解决方案3】:

    请检查VS Code终端当前所在的文件夹是否是正在执行的python文件的父文件夹。

    解决方案:

    1. 您可以在终端使用命令“cd folder_name”进入python文件的父文件夹:

    2. 或者在设置文件“settings.json”中使用如下设置:

      "python.terminal.executeInFileDir": true,

      在执行运行命令前会自动跳转到当前文件的父文件夹:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-27
      • 1970-01-01
      • 2017-01-15
      • 2016-03-05
      • 2020-04-13
      • 2015-07-12
      相关资源
      最近更新 更多