gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:01:09 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com