-1

I have to read a simple file named 'highscore.txt' in my slakes.py file. Both are located in same folder. But idk why I am getting file not found error Code:

with open('highscore.txt', 'r') as f:
    high_score = f.read()
Klim Bim
  • 484
  • 2
  • 7
  • Are you running Python from the same folder as well? When reading a relative path, Python reads from the current working directory (not the script file). Eg... ``` $ 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] No such file or directory: highscores.txt ``` – Mat May 11 '21 at 09:13

3 Answers3

0

Try using module named csv The following code is a basic code to read a file:

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

You can use any variables

Saffron-codes
  • 158
  • 1
  • 9
0

This part of code check if file is exist. If not - create this empty file and read this file.
I recommend using the full path to your file like /home/user/folde/subfolder/file.txt
I hope this helps you.

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()
    
Andrii
  • 74
  • 6
0

Please check whether the folder where the VS Code terminal is currently located is the parent folder of the python file being executed.

Solution:

  1. You could use the command "cd folder_name" in the terminal to go to the parent folder of the python file:

    enter image description here

  2. Or use the following settings in the settings file "settings.json":

    "python.terminal.executeInFileDir": true,

    It will automatically go to the parent folder of the current file before executing the run command:

    enter image description here

Jill Cheng
  • 9,179
  • 1
  • 20
  • 25