Python 不关闭最后一个文件

Python doesn't close the last file

我创建此代码是为了获取文件夹中的所有 excel 文件,并为每个文件中的每个 sheet 创建一个 csv 文件。此脚本工作正常,但有时转换后的最后一个 Excel 文件仍被文件系统上的 python 锁定。谁能帮助我了解发生了什么?

import sys
from os import listdir
from os.path import isfile, join
import pandas as pd
import csv
import re

def removeEspecialCharacters(obj):
    if isinstance(obj, str) :
        retorno = re.sub('[(\x90|\x8F)]','',obj).replace("\r","").replace("\n","")
    else:
        retorno = obj
        
    return retorno

myFolder = r'C:\Users\myuser\Downloads\ConvertFilesToCsv'
myFiles = [f for f in listdir(myFolder) if isfile(join(myFolder, f))]

for x in range(len(myFiles)):   
    if (myFiles[x].lower().endswith('.xls') or myFiles[x].lower().endswith('.xlsx') or myFiles[x].lower().endswith('.xlsb')):
        print('Converting file: '+myFiles[x]);
        if (myFiles[x].lower().endswith('.xlsb')):
            file = pd.ExcelFile(myFolder+'\'+myFiles[x], engine='pyxlsb')
        else:
            file = pd.ExcelFile(myFolder+'\'+myFiles[x])
    
        for mySheetName in file.sheet_names:
            df = pd.read_excel(file, sheet_name=mySheetName)
            df = df.applymap(removeEspecialCharacters)
            csvFileName = myFolder+'\'+myFiles[x].replace('.xlsx','').replace('.xlsb','').replace('.xls','')+'_'+mySheetName+'.csv'
            df.to_csv(csvFileName,encoding='utf-8-sig',index=False,sep=",",quoting=csv.QUOTE_NONNUMERIC,quotechar="\"",escapechar="\"",decimal=".",date_format='%Y-%m-%d')#,quotechar='\'', escapechar='\')
        file.close()
        file = ''

注意: 这是代码格式的注释。

我觉得你的代码没问题。我建议您使用上下文管理,类似于 the doc,如下所示:

for filename in myFiles:   
    extension = filename.split('.')[-1]

    # you didn't seem to check xlsb in your code
    if extension not in ['xls', 'xlsx', 'xlsb']: 
        continue

    kwargs = {'engine': 'pyxlsb'} if extension=='xlsb' else {}

    with pd.ExcelFile(myFolder + '\' + filename, **kwargs) as file:
        # do other stuff with file
        ...
        # you don't need to close file here
        # file.close()