我創建了這段代碼來獲取一個檔案夾中的所有 excel 檔案,并為每個檔案中的每個作業表制作一個 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 = ''
uj5u.com熱心網友回復:
注意:這是對代碼格式的注釋。
你的代碼對我來說看起來不錯。我建議您使用類似于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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/488492.html
