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

标签 python python-3.x file io

当我使用 "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 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

关于Python 3 : ResourceWarning: unclosed file <_io. TextIOWrapper 名称 ='PATH_OF_FILE',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50752791/

相关文章:

python - 如何从我需要的文本中跳过或截断字符或符号。网页抓取与 BeautifulSoup

python - PyQt5 QScrollArea 不滚动,而是调整项目大小

python - 生成器作为函数参数

Android:是否可以使用 openFileOutput 函数创建媒体文件

java - 无法访问 res 文件夹?

ios - Swift - 如何访问设备上的所有 pdf 文件

当变量/方法放置在函数内部时,Python 2.7 的作用域问题

python - 写入 CSV 文件时如何从列表中选择合适的数据?

python - 是否可以在没有单独的迭代器对象的情况下进行对象迭代?

python-3.x - celery 花 API 结果未返回