Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

What am I missing?

like image 525
Minisha Avatar asked Jun 08 '18 03:06

Minisha


1 Answers

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

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
like image 74
MontyPython Avatar answered Sep 24 '22 13:09

MontyPython