Python 3:ResourceWarning:unclosed文件

问题描述 投票:7回答:1

当我使用“python normalizer / setup.py test”在python中运行测试用例时,我得到以下异常

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

在代码中,我正在阅读如下的大文件:

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

我错过了什么?

python python-3.x file io
1个回答
5
投票

来自Python unclosed resource: is it safe to delete the file?

此ResourceWarning意味着您打开了一个文件,使用它,但后来忘记关闭该文件。当Python注意到文件对象已经死亡时,Python会为你关闭它,但这只会在经过一段时间后才会发生。

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
© www.soinside.com 2019 - 2024. All rights reserved.