Anyone knows about Python What is the mistake in the fllowing code?

Hi,

so there is my code;


employee_file = open("employees.txt", "r")

print(employee_file.readable())

employee_file.close()

The error was that the file can’t be located.

Now please tell me where is my mistake. When I did that an error was printed on line 2 which is the first code. I checked the spelling several times and it seems correct.
THe employees file.txt is also saved in the same directory with my other pythons (in easier words, it is saved in the correct place and it is saved as .txt) so I can’t find the problem. PLease help?

I realize now that it is not responding to anycode. Pycharm is unbelievable hard. ALl of sudden nothing is working. I tried new project, I saved file at .py and I work with them, no project is working end, NOTHIUNG; NADA

Hi, sorry about that. These kind of error can be quite frustrating at times!! Doesnt seem like their is a mistake in your code.
Question: how are you calling the python file? Are you calling it from the command line terminal like so:

python filename.py

If so, it could be an issue of the working directory. You could easily check this by adding into the python file:

import os
print ("Current working directory is ", os.getcwd())

This will print the working/current directory from which the python file is executing or was called. It is in this directory that the executing python file will look for the employees.txt when using relative paths. To use the script as you wrote it, you would have to navigate to the folder manually in the command line and only then call the python file.

If you do not want to do this manually, you are better off changing your file to read the absolute paths instead of the relative paths.

# Since your file is in the same folder as the python file,
# you can find the path to python file and use that path for your text file

import os
# To get the path of the python file
python_file = os.path.abspath(__file__)

# To get the directory path for the file path obtained above
dir_path = os.path.dirname(python_file)

# Absolute path to the file
file_path = os.path.join(dir_path, "employees.txt")

# Just to see that its now possible to call from any working directory
print("Directory path to python file is ", dir_path)
print("Current working directory is ", os.getcwd())
print("file path is", file_path)

employee_file = open(file_path, "r")
for line in employee_file:
	print(line)
employee_file.close()

I added print statements so you can see whats happening, you can remove them. With that, regardless of which working directory you call the python file, if the python file and the employees.txt are in the same folder, the python file will find it by finding its own path and using that path to get the employees.txt file.
I am not sure about the .readable() method i assumed its a true/false method.

Hope that helps!
regards,