admin管理员组

文章数量:1660166

错误描述:

程序运行过程中,报错后,调用删除文件时显示另一个程序正在使用文件,无法删除。

但是本人并没有在外面打开该文件,也没有什么东西调用这个文件。很奇怪

报错如下:

过程:

然后打断点发现,我是用python读取csv文件的时候是按照chunk读取的,修改读取方式,该错误消失。所以应该是删除文件的时候,该文件还是打开读取的状态所以不能访问并删除

解决:

没有关闭,那将文件关闭就好了。使用with open打开文件后用pandas读取文件,删除之前先关闭文件。

 代码修改如下:

with open(file_path) as file:
    kpi = pd.read_csv(file, chunksize=100000)  # 默认读取编码为UTF-8
    for i, chuck in enumerate(kpi):
        file.close()
        if os.path.exists(file_path):
            os.remove(file_path)
            print('删除成功')

———————————————————————————————————————————

open打开后,如果没有指定编码,pandas读取文件的时候可能会报错,所以新增一个编码判断,并在open中指定文件编码

判断文件编码

from chardet.universaldetector import UniversalDetector
from pandas.errors import EmptyDataError


def get_encoding(file):
    detector = UniversalDetector()
    with open(file, 'rb') as f:
        line = f.readlines()
        if len(line) <= 1:
            raise EmptyDataError('文件错误!')
        else:
            detector.feed(line[0])
            detector.feed(line[1])
    detector.close()
    if detector.result['encoding'] == 'GB2312':
        encoding = 'gbk'
    elif detector.result['encoding'] == 'ascii':
        encoding = 'utf-8'
    else:
        encoding = 'utf-8'
    return encoding

encoding=get_encoding(file_path)
with open(file_path,encoding=encoding) as file:
    kpi = pd.read_csv(file, chunksize=100000)  # 默认读取编码为UTF-8
    for i, chuck in enumerate(kpi):
        file.close()
        if os.path.exists(file_path):
            os.remove(file_path)
            print('删除成功')

本文标签: 报错文件Python