-1

I am stuck to this weirdly small problem for like 3 hours and i just can't find the fix of it. Here look at the problem I'm trying to read a .txt file(greetings.txt) which contains a simple message and both- the .txt file and the program to read the file (readingfile.py) are inside the same folder, but still when i try to run the program which should return the text inside the .txt file , instead , it's throwing an error FileNotFoundError: [Errno 2] No such file or directory: 'greetings.txt' If you think you familiar with this issue please help.

The code is written below and i will be also attaching an image please check that as well.Go through this link to view the image

with open('greetings.txt') as file:
    content = file.read()
print(content)
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Sunyog Lodhi
  • 3
  • 2
  • 3
  • Check the directory and the method you are using to run the file, if you are in VS code try clicking the run button (on top right) that will automatically change the directory. –  Jan 22 '22 at 05:40
  • Try giving the full path – Abhishek Rai Jan 22 '22 at 05:42
  • Vscode is running the code directly from the `my_work` folder, as this is your workspace, and where the terminal command gets ran. Your file doesn't exist there, as the error says. If you opened that subfolder as its own vscode workspace, it would start working – OneCricketeer Jan 22 '22 at 06:37

1 Answers1

0

Your corrent folder is not the parent folder of the script, which is coincidentally also where your greetings.txt file is located.

To fix that, use __file__ to get the absolute path of the executing script, and then join with the parent path to get the absolute path of the text file.

For instance:

import os

path_to_file = os.path.join(os.path.dirname(__file__), 'greetings.txt')

with open(path_to_file) as file:
    ...

Alternatively, in Python 3.x, the above code can be simplified even further by relying on pathlib module:

from pathlib import Path

content = (Path(__file__).parent / 'greetings.txt').read_text()
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
  • hey thanks for answering, i didn't know the concept about parent directory, i am a student learning python so i wanted to make my programming journey well organized by keeping distinct topics in distinct folders as you might have seen in the image. Thanks a lot again. – Sunyog Lodhi Jan 22 '22 at 08:03
  • @Sunyog no problem, glad it worked out. If it was helpful, you can consider accepting the answer, just so it can mark the question as resolved for others, though of course it’s not any kind of requirement. – rv.kvetch Jan 22 '22 at 13:16