Alvaro Enrique Alvaro Enrique - 21 days ago 4
Linux Question

How can I open debian files with Python?

I got an error when I'm trying to read "etc/network/interfaces" in debian with python, saying the file or directory not exists..

file = open("etc /network/interfaces", "r")
content =
print content

Can anyone help me?


First, fix your path (remove the space, and put a / before etc since it is in your root directory):

file = open("/etc/network/interfaces", "r") 

Next make sure to close the file object when you are done with it to free up system resources:


Better yet, use a context manager:

with open("/etc/network/interfaces", "r") as file:
    content =
    print content

Now, as soon as the context manager is exited, the file will be closed automatically.

Bonus tip: "r" can be omitted as the second argument to open() because this is the default argument: open("/etc/network/interfaces"). However, there is nothing wrong with explicitly providing the mode even if it is "r".