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
docxfiles are zip files so you should open them in binary mode (mode='rb'). Also you can open them withzipfile.ZipFile('/Users/name/Desktop/Trip.docx')and access the archived files.python-docxwould be more useful.