1

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?

K.Land_bioinfo
  • 170
  • 1
  • 3
  • 12

2 Answers2

1

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.

Community
  • 1
  • 1
K.Land_bioinfo
  • 170
  • 1
  • 3
  • 12
0

You can provide the full path in open(), not only the filename:

file = open("/etc/yate/input.txt", "wb")

Full code:

try:
     file = open("/etc/yate/input.txt", "wb")
except IOError:
     print "Error"
else:
     dosomething()
finally:
     file.close()

But, as with works as a context manager, you can make your code much shorter using the power of with.

Code:

try:
     with open("input.txt", "wb") as file:
         dosomething()   
except IOError:
     print "Error"
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57