(Python)无法从目录中打开文件

2024-04-26 21:11:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我想打开文件作为输出。你知道吗

It turned out "exit"

但是,我想read文件或write文件。通过测试,似乎没有 IOError。如何打开文件?你知道吗

我试了好几个密码,仍然找不到打开它的方法。你知道吗

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

然后,我将“docx”改为“doc”,添加“r”模式并调用它。你知道吗

我试过:

    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


Tags: 文件readmyexitopenoutusersfile
2条回答

打开文件时,必须指定意图。 对于写作来说:

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

你测试过文件是否在块的末尾打开了吗?因为我想你会发现的。try:except:block的“finally”部分中的代码是服从的,不管是否有异常。你知道吗

从python文档中:

如果finally存在,则指定“cleanup”处理程序。执行try子句,包括任何except和else子句。如果任何子句中发生异常且未处理,则会临时保存该异常。finally子句被执行。如果存在保存的异常,则会在finally子句的末尾重新引发该异常。如果finally子句引发另一个异常,则将保存的异常设置为新异常的上下文。如果finally子句执行return或break语句,则丢弃保存的异常:

相关问题 更多 >