1
votes

I want to open the file as output.

It turned out "exit"

However, I want to read the file or write the file. Through the test, it seems not the IOError. How to open the file?

I tried several codes and still could not find the way to open it.

try:
    my_file_handle=open("/Users/name/Desktop/Trip.docx")
except IOError:
    print("File not found or path is incorrect")
finally:
    print("exit")

Then, I changed "docx" to "doc" and add 'r' mode and call it.

I tried:

    try:
        my_file_handle=open('/Users/name/Desktop/Trip.doc','r')
        my_file_handle.read()
        print("hi")
    except IOError:
        print("File not found or path is incorrect")
    finally:
        print("exit")

it turned out "exit" and my_file_handle.read()

File"/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final)

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in position 0: invalid continuation byte

2
What’s your error message? I believe when opening a file you need to specify whether you’re reading, writing, etc. - K-Log
I want to read it. - AAlex
What are you planning to do with the open file? docx files are zip files so you should open them in binary mode (mode='rb'). Also you can open them with zipfile.ZipFile('/Users/name/Desktop/Trip.docx') and access the archived files. - mhawke
I tried "rb". It could not work. - AAlex
Again, what do you want to do with the file once opened? Perhaps a library like python-docx would be more useful. - mhawke

2 Answers

2
votes

Have you tested if the file is actually open at the end of the block? Because I think you'll find it is. The code in the 'finally' part of a try: except: block is obeyed regardless of whether there is an exception or not.

From the python documentation:

If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause. If the finally clause raises another exception, the saved exception is set as the context of the new exception. If the finally clause executes a return or break statement, the saved exception is discarded:

0
votes

When opening the file, you have to specify your intensions. For writing that would be:

    my_file_handle=open("/Users/name/Desktop/Trip.docx","w")