gpt4 book ai didi

python - 用户警告 : Calling close() on already closed file. 警告 ("Calling close() on already closed file.")

转载 作者:行者123 更新时间:2023-12-04 16:25:15 31 4
gpt4 key购买 nike

此错误显然源于 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.")
我把保存部分放在 try except根据 this help doc 阻止,但我一定是做错了。
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----')

最佳答案

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

关于python - 用户警告 : Calling close() on already closed file. 警告 ("Calling close() on already closed file."),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66035566/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com