简体   繁体   中英

(Python) cannot open the file from directory

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

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:

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM