Python:未找到文件错误。没有指定这样的文件或目录

2024-10-04 01:29:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: 文件代码pytxt文件夹readas错误
3条回答

这部分代码检查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()
    

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

解决方案:

  1. 您可以使用终端中的命令“cd folder_name”转到python文件的父文件夹:

    enter image description here

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

    "python.terminal.executeInFileDir": true,

    在执行run命令之前,它将自动转到当前文件的父文件夹:

    enter image description here

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

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

您可以使用任何变量

相关问题 更多 >