Search code examples
pythonpython-3.xpathfilepath

Why is relative path not working in python 3?


I can't get relative path in python3 to work i used it before but now when i try to read a text file in same folder(directory) it shows

Traceback (most recent call last):
  File "F:\python project\main_programm\main.py", line 1, in <module>
    open("text.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'text.txt'

the code is just

open("text.txt")

i have no idea why it is doing this the directory has main.py and text.txt (autocomplete works!)

so i searched online and found a os command to find working directory

import os
print(os.getcwd())

and i get this

G:\PyCharm Community Edition 2020.3.1\jbr\bin

also when i run this exact code through terminal(cmd) with python "F:\python project\main_programm\main.py" i get C:\Users\$my_user_name$


Solution

  • Maybe this helps you out:

    file = open('txt.txt')
    content = file.read()
    file.close()