简体   繁体   English

Python我应该在阅读后关闭文件

[英]Python should I close the file after reading

I'm using Django 1.10 and Python 3.5.3 我正在使用Django 1.10和Python 3.5.3

In one of the views the user is sending a file and I'm reading it like that: 在其中一种视图中,用户正在发送文件,而我正在这样读取文件:

    def create(self, request, *args, **kwargs):
        file_serializer = self.get_serializer(data=request.data)
        file_serializer.is_valid(raise_exception=True)
        if file_serializer.is_valid():
            if 'file' in request.data:

                # hash file
                hasher = hashlib.md5()
                read_file = request.data['file'].read()
                hasher.update(read_file)
                current_file_hash = hasher.hexdigest()

My question is - Should I close the file afterwards? 我的问题是-之后我应该关闭文件吗? Seems like I don't actually open it. 好像我实际上没有打开它。

From what I can tell, request.data['file'] is actually an open file descriptor, not a filename. 据我所知, request.data['file']实际上是一个打开的文件描述符,而不是文件名。 If you know request will take care of cleaning up its own resources, there's obviously no need to explicitly close the file. 如果您知道request将负责清理其自身的资源,那么显然无需显式关闭文件。 Otherwise, close it with request.data['file'].close() . 否则,请使用request.data['file'].close() In that case, it would be best to wrap the entire function body in a try / finally -block, to assure the file gets closed no matter what: 在那种情况下,最好将整个函数体包装在try / finally -block中,以确保无论如何都可以关闭文件:

try:
    # read from file etc.
finally:
    request.data['file'].close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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