无法拆卸 Pandas read_csv 使用的临时文件

Unable to teardown temporary file used by Pandas read_csv

我的单元测试拆解代码没有删除文件

test_utility1.dat

我什至试过 os.remove 也没有成功。我不明白为什么我的进程在出现错误后仍保留该文件。我在 python 3.6 上 运行 并使用 Pycharm 作为我的 IDE。我的所有测试都通过了,除了拆解。

我的意思是我试图模拟,但我没有运气(新手,我只是无法理解或掌握这个概念)。所以我不得不创建一个临时文件并将其删除。我有同样的问题,所以我认为如果我尝试 textfixture 库会更好。但同样的错误。

更新了我的 POST

请帮忙。谢谢

protoype7.py

import sys
import pandas

def create_utility_config_dataframe(a):

cols = ['Name', 'D', 'L', 'J', 'H', 'E', 'M', 'RF', 'AF']
try:
    return pandas.read_csv(a, sep='\t', usecols=cols)

except Exception as ve:
    ve = (str(ve) + "\n\nPlease ensure utility config '%s' exist and is correctly formatted (tab delimited)" %a)
    sys.exit(ve)

test2_prototype7.py

from prototype7 import create_utility_config_dataframe
import os
import unittest

class TestCreateUtilityConfigDataFrame(unittest.TestCase):

    @classmethod
    def tearDownClass(cls):
        os.remove('test_utility1.dat')

    def test_when_parameters_is_invalid(self):

        self.assertRaises(SystemExit, create_utility_config_dataframe,'test_utility1.dat')

错误日志

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'test_utility1.dat'

test_utility1.dat

Name.D.L.J.H.E.M.RF.AF
line1.150.4.2.150.2.Copper.1.true

嗯,分辨率如下

初始代码片段

self.assertRaises(SystemExit, create_utility_config_dataframe, a)

新代码片段

with self.assertRaises(SystemExit):
     create_utility_config_dataframe(a)

这解决了问题。这是 assertRaise 代码的问题。我不完全确定为什么,但是如果我使用 with 语句,它现在可以正常工作了。