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 报错文件被占用 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1729845920a1215128.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论