Search code examples
pythonubuntuiopathfile-exists

Python - How to open or create a file in root folder on Ubuntu?


I want to create (or open if existed) a file with python with path /etc/yate/input.txt. Here is my code:

try:
     file = open("input.txt", "wb")
except IOError:
     print "Error"
with file:
     doSomething()

and I get "Error" message

How can I fix it?


Solution

  • You can import os.path, then check if the file exists. This might have also been answered before here How do I check whether a file exists using Python?

    Code:

    import os.path
    

    Now, check if that file name exists in your file path:

    file_exists = os.path.isfile(/etc/yate/input.txt)
    
    if file_exists:
        do_something
    

    Or, if you want to do something, like creating and opening the file if it does not exist:

    if not file_exists:
        do_something_else
    

    Update: In the link I provided, there are other ways to do this, like using pathlib instead of os.path.