Hi,
I am having a problem when I'm trying to open and read a file with python.
My code goes as follows:

def main():
    f = open('nummer.txt', 'r')
    text = f.readlines()
    print(text)

main()

But when I try to run the code, I get an error. (No such file or directory).
I have saved the nummer.txt file in the same folder as the code, what is wrong here?

Probably, the way you're executing the script is making the default directory other than where you have the file. Try fully qualifying the file name.

are you sure the file you want to open is in the same directory as your python script?

Edited 4 Years Ago by glenwill101

if i have understood this correctly, i can access the file via its location? or do i have to write the file in python script?
i thought i could access the file with just type the name of the file/ its location, and then read it. (i tried with /Users/...../nummer.txt)
i am 100% sure the file is in the same folder as the pyton file.

Edited 4 Years Ago by rocket3443

Just because it would be nice.
What did you do to make it work?

Another option would be to write Python code that will find the file and its path.

Edited 4 Years Ago by vegaseat

Automatically executing in the current directory is considered dangerous as an attacker could add their own bash for example in the current directory. It would be executed if the current directory is searched first and could do anything the programmer wished. You can add
PATH=$PATH:.
and export it to .bashrc if you want. In addition we have all been in the situation where there are multiple programs with the same name and we run the wrong one. This is especially true when we duplicate a program name that is in the Python library, like abc.py. The program in the current directory would be imported if it is the first one found.

This article has been dead for over six months. Start a new discussion instead.