Python 3:ResourceWarning:未关闭文件< _io.TextIOWrapper名称='PATH_OF_FILE' [英] Python 3: ResourceWarning: unclosed file <_io.TextIOWrapper name='PATH_OF_FILE'

查看:172
本文介绍了Python 3:ResourceWarning:未关闭文件< _io.TextIOWrapper名称='PATH_OF_FILE'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用"python normalizer/setup.py test在python中运行测试用例时 "我遇到了以下例外情况

When I run the test cases in python with "python normalizer/setup.py test " I am getting the below exception

 ResourceWarning: unclosed file <_io.TextIOWrapper name='/Users/workspace/aiworkspace/skillset-normalization-engine/normalizer/lib/resources/skills.taxonomy' mode='r' encoding='utf-8'>

在代码中,我正在读取一个大文件,如下所示:

In code I am reading a big file like below:

def read_data_from_file(input_file):
    current_dir = os.path.realpath(
        os.path.join(os.getcwd(), os.path.dirname(__file__)))
    file_full_path = current_dir+input_file
    data = open(file_full_path,encoding="utf-8")
    return data

我想念什么?

推荐答案

来自

此ResourceWarning意味着您打开了一个文件,使用了它,但随后却忘记了关闭该文件.当发现文件对象已死时,Python会为您关闭它,但这只会在未知的时间过去之后发生.

This ResourceWarning means that you opened a file, used it, but then forgot to close the file. Python closes it for you when it notices that the file object is dead, but this only occurs after some unknown time has elapsed.

def read_data_from_file(input_file):
    current_dir = os.path.realpath(
        os.path.join(os.getcwd(), os.path.dirname(__file__)))
    file_full_path = current_dir+input_file
    with open(file_full_path, 'r') as f:
        data = f.read()
    return data

这篇关于Python 3:ResourceWarning:未关闭文件&lt; _io.TextIOWrapper名称='PATH_OF_FILE'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆