用户警告:在已关闭的文件上调用 close()。警告("Calling close() on already closed file.")

UserWarning: Calling close() on already closed file. warn("Calling close() on already closed file.")

这个错误显然源于 xlsxwriter。我不确定它来自我的代码的哪一行,因为我的编辑器 Visual Studio 2019 每次我尝试调试时都会崩溃。但是,我在笔记本电脑上使用 VPN 和远程桌面连接时遇到此错误。如果我 运行 来自远程机器的相同代码,我不会收到错误。不过,该错误似乎不会影响输出,因为脚本已成功完成并保存。但是,我该如何摆脱这个错误?

我的代码:

import requests
from bs4 import BeautifulSoup
import pandas as pd
from pandas import ExcelWriter
from datetime import datetime
import os

#set the headers as a browser
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
#set up file name
file_path = r"C:\Users\jpilbeam"
excel_file = 'bargetraffic' + str(datetime.now().strftime('_%m_%d_%Y')) + '.xlsx'
excel_file_full = os.path.join(file_path, excel_file)

lockName = ['Dresden Island Lock', 'Brandon Rd Lock', 'Lockport Lock']
lockNo = ['02', '03', '04']

results = []
for lock in lockNo: 
    url = 'https://corpslocks.usace.army.mil/lpwb/xml.lockqueue?in_river=IL&in_lock=' + lock
    #print (url)
    link = requests.get(url).text
    soup = BeautifulSoup(link,'lxml')
    
    #get elements of row tags
    rows = soup.find_all('row')

    sheet = pd.DataFrame()
    for row in rows:
        name = row.find('vessel_name').text.strip()
        no = row.find('vessel_no').text.strip()
        dir = row.find('direction').text.strip()
        barno = row.find('num_barges').text.strip()
        arr = row.find('arrival_date').text.strip()

        try:
            end = row.find('end_of_lockage').text.strip()
        except:
            result = ''

        df = pd.DataFrame([[name,no,dir,barno,arr, end]], columns=['Name','Vessel No.','Direction','Number of Barges','Arrival', 'End of Lockage'])
        sheet = sheet.append(df,sort=True).reset_index(drop=True)

    results.append(sheet)


def save_xls(list_dfs, xls_path):
    with ExcelWriter(xls_path) as writer:
        for n, df in enumerate(list_dfs):
            df.to_excel(writer,'%s' %lockName[n],index=False,)
        writer.save()

save_xls(results,excel_file_full)
print('----done----')

错误:

C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\xlsxwriter\workbook.py:329: UserWarning: Calling close() on already closed file.
  warn("Calling close() on already closed file.")

我按照this help doc将保存部分放在try except块中,但一定是我做错了

while True:
    try:
        def save_xls(list_dfs, xls_path):
            with ExcelWriter(xls_path) as writer:
                for n, df in enumerate(list_dfs):
                    df.to_excel(writer,'%s' %lockName[n],index=False,)
                writer.save()

        save_xls(results,excel_file_full)
    except xlsxwriter.exceptions.FileCreateError as e:
        print(e)
print('----done----')

出现警告是因为您在 with 语句中调用 to_excel(),一旦文件离开范围,该语句实际上 closes/saves 文件。然后您调用 save() 尝试再次关闭该文件,但由于它已经关闭,您会收到警告(不是错误或异常)。