Python 3:ResourceWarning:unclosed文件< _io.TextIOWrapper name =’PATH_OF_FILE’

Python 3: ResourceWarning: unclosed file <_io.TextIOWrapper name='PATH_OF_FILE'

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

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

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

1
2
3
4
5
6
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未关闭的资源:删除文件安全吗?

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.

1
2
3
4
5
6
7
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