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()


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?

Recommended Answers

All 6 Replies

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?

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.

nvm, it worked :)

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.

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
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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.