簡體   English   中英

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中運行測試用例時,我得到以下異常

 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:刪除文件是否安全?

此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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM