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()
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()
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
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()
Please check whether the folder where the VS Code terminal is currently located is the parent folder of the python file being executed.
Solution:
You could use the command "cd folder_name
" in the terminal to go to the parent folder of the python file:
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: