0

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?

5
Contributors
6
Replies
8
Views
4 Years
Discussion Span
Last Post by woooee
0

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.

0

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

Edited by glenwill101

0

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 by rocket3443

0

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 by vegaseat

0

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.