with open('test_result0.txt', 'r',encoding='utf-8') as f, openpyxl.Workbook() as wb: AttributeError: __enter__

时间: 2023-12-14 11:03:27 浏览: 59
这个错误通常是因为 `openpyxl.Workbook()` 没有返回一个 `with` 上下文管理器。解决方法是将 `openpyxl.Workbook()` 的返回值赋值给一个变量,然后将这个变量用于 `with` 语句。修改后的代码如下: ```python import openpyxl # 打开txt文件和Excel文件 with open('test_result0.txt', 'r', encoding='utf-8') as f: wb = openpyxl.Workbook() sheet = wb.active sheet.title = 'Result' # 逐行读取txt文件并处理 for line in f: # 将"的tf-idf值为"替换成tab line = line.replace('的tf-idf值为', '\t') # 以tab为分隔符,分割字符串并保存到Excel文件中 parts = line.split('\t') sheet.append([parts[0], float(parts[1])]) # 保存Excel文件 wb.save('result.xlsx') ``` 这里将 `openpyxl.Workbook()` 的返回值赋值给 `wb` 变量,然后将这个变量用于 `with` 语句。这样就可以避免上述错误。
相关问题

import os import re import xlrd import xlwt print("当前路径:", os.getcwd()) file_path = os.getcwd() n = re.split(r'\\', file_path) path = file_path + '\\' + n[5] + ".xls" workbook = xlwt.Workbook(encoding='utf-8') for filename in os.listdir(file_path): if (os.path.splitext(filename)[-1] == ".txt"): data_sheet = workbook.add_sheet(filename[:-4]) data_sheet.write(0, 0, 'No.') data_sheet.write(0, 1, 'test_file_name') data_sheet.write(0, 2, 'rate_ratio') with open(filename, 'r') as f: data = f.readlines() key = 1 sheet_row = 1 while key >= 0: ret = re.search(".bin", data[key]) if ret != None: #print(key) #print(data[key]) #write to excel data_sheet.write(sheet_row, 0, key) data_sheet.write(sheet_row, 1, data[key]) sheet_row = sheet_row + 1 else: break key = key + 1 count = key - 1 count_idx = 1 sheet_row = 1 while key >= 0: ret = re.match("Tensor rate is ", data[key]) if ret != None: #print(count_idx, data[key]) data_sheet.write(sheet_row, 2, data[key][14:]) sheet_row = sheet_row + 1 count_idx = count_idx + 1 key = key + 1 if count_idx > count: break workbook.save(path) 优化上面的代码

上面的代码可以进行如下的优化: 1. 使用`os.path.join()`代替手动拼接路径,可以保证路径的正确性。 2. 使用`with open()`语句打开文件,可以自动管理文件的打开和关闭。 3. 使用正则表达式的`match()`方法代替`search()`方法,因为`search()`方法会在整个字符串中查找匹配,而`match()`方法只会从字符串开头开始匹配。 4. 将重复的代码段抽取为函数,以提高代码的可读性和复用性。 下面是优化后的代码: ```python import os import re import xlwt def process_file(filename, data_sheet): with open(filename, 'r') as f: data = f.readlines() sheet_row = 1 for line in data: if line.endswith('.bin\n'): data_sheet.write(sheet_row, 0, sheet_row) data_sheet.write(sheet_row, 1, line) sheet_row += 1 elif line.startswith("Tensor rate is "): data_sheet.write(sheet_row, 2, line[14:]) sheet_row += 1 def main(): file_path = os.getcwd() n = re.split(r'\\', file_path) path = os.path.join(file_path, n[5] + ".xls") workbook = xlwt.Workbook(encoding='utf-8') for filename in os.listdir(file_path): if os.path.splitext(filename)[-1] == ".txt": data_sheet = workbook.add_sheet(filename[:-4]) data_sheet.write(0, 0, 'No.') data_sheet.write(0, 1, 'test_file_name') data_sheet.write(0, 2, 'rate_ratio') process_file(filename, data_sheet) workbook.save(path) if __name__ == '__main__': main() ``` 通过将重复的代码段抽取为函数`process_file()`,提高了代码的可读性和可维护性。同时,使用`os.path.join()`和`with open()`语句更加规范和安全地处理路径和文件操作。

修改这个是吗data = xlrd.open_workbook(inpath, encoding_override='utf-8')

`xlrd.open_workbook()` 函数的 `encoding_override` 参数是用于指定文件编码方式的,使用 `utf-8` 编码方式应该可以解决 `UnicodeEncodeError` 错误。你可以尝试使用以下代码: ``` import xlrd inpath = 'your_excel_file_path' data = xlrd.open_workbook(inpath, encoding_override='utf-8') ``` 需要注意的是,虽然使用 `utf-8` 编码方式可以解决 `UnicodeEncodeError` 错误,但这并不保证可以正确地读取 Excel 文件中的所有内容。如果 Excel 文件中包含复杂的内容,如公式、宏等,建议使用专门的 Excel 处理库,如 openpyxl、pandas 等。

相关推荐

#!/bin/env python import numpy as np import pandas as pd import openpyxl,os df_csv = pd.read_csv(r'Permance_a.csv',index_col=0,encoding='utf-8') df_csv.to_excel(r'Permance_a.xlsx') # 打开Excel文件 wb = openpyxl.load_workbook('Permance_a.xlsx') # 选择第一个工作表 ws = wb.active # 循环遍历每一个单元格 for row in ws.iter_rows(): for cell in row: # 判断单元格是否包含% if '%' in str(cell.value): # 将单元格格式设置为数字格式 cell.number_format = '0.00%' # 将单元格值除以100并重新赋值给单元格 cell.value = float(cell.value.strip('%')) / 100 # 保存Excel文件 wb.save('Permance_a.xlsx') # 源表格和目标表格的文件名 source_file = r'Permance_a.xlsx' target_file = r'Permance.xlsx' source_end_col = 8 # 结束列 source_start_col = 5 # 开始列 source_start_row = [2,12,22,32] source_end_row = [11,21,31,41] target_end_col = 6 # 结束列 target_start_col = 3 # 开始列 target_start_row = [7,35,21,49] target_end_row = [16,44,30,58] # 打开两个工作簿 wb1 = openpyxl.load_workbook(source_file) ws1 = wb1.active target_ws_name = 'sd' + source_file[-6] wb2 = openpyxl.load_workbook(target_file) wb2.active.title = target_ws_name ws2 = wb2.active # 将源表格的数据覆盖到目标表格中 for i in range(len(source_start_row)): for row in range(source_start_row[i], source_end_row[i]+1): for col in range(source_start_col, source_end_col+1): value = ws1.cell(row=row, column=col).value ws2.cell(row=target_start_row[i]+row-source_start_row[i], column=target_start_col+col-source_start_col, value=value) # 保存目标表格 wb2.save(target_file) 修改以上代码,将目标文件中数据引用源中工作明修改为target_ws_name

#!/usr/bin/env python #coding: utf-8 import os from time import time from datetime import datetime from netmiko import ConnectHandler from openpyxl import Workbook from openpyxl import load_workbook def read_device_excel( ): ip_list = [] wb1 = load_workbook('E:\/Users/Wayne_Peng/Desktop/cs_lab.xlsx') ws1 = wb1.get_sheet_by_name("Sheet1") for cow_num in range(2,ws1.max_row+1): ipaddr = ws1["a"+str(cow_num)].value ip_list.append(ipaddr) return ip_list def get_config(ipaddr): session = ConnectHandler(device_type="huawei", ip=ipaddr, username="mtlops", password="cisco,123", banner_timeout=300) print("connecting to "+ ipaddr) print ("---- Getting HUAWEI configuration from {}-----------".format(ipaddr)) # config_data = session.send_command('screen-length 0 temporary') # config_data = session.send_command('dis cu | no-more ') # command = 'display version | display cpu-usage | display memory-usage' # config_data = session.send_command(command) commands = ['display version', 'display cpu-usage', 'display memory-usage'] config_data = '' for cmd in commands: output = session.send_command_timing(cmd) config_data += f'{cmd}\n{output}\n' session.disconnect() return config_data def write_config_to_file(config_data,ipaddr): now = datetime.now() date= "%s-%s-%s"%(now.year,now.month,now.day) time_now = "%s-%s"%(now.hour,now.minute) #---- Write out configuration information to file config_path = 'E:\/Users/Wayne_Peng/Desktop/' +date verify_path = os.path.exists(config_path) if not verify_path: os.makedirs(config_path) config_filename = config_path+"/"+'config_' + ipaddr +"_"+date+"_" + time_now # Important - create unique configuration file name print ('---- Writing configuration: ', config_filename) with open( config_filename, "w",encoding='utf-8' ) as config_out: config_out.write( config_data ) return def main(): starting_time = time() ip_list = read_device_excel() for ipaddr in ip_list: hwconfig = get_config(ipaddr) write_config_to_file(hwconfig,ipaddr) print ('\n---- End get config threading, elapsed time=', time() - starting_time) #======================================== # Get config of HUAWEI #======================================== if __name__ == '__main__': main() 加一段gevent,def run_gevent()

最新推荐

recommend-type

pre_o_1csdn63m9a1bs0e1rr51niuu33e.a

pre_o_1csdn63m9a1bs0e1rr51niuu33e.a
recommend-type

matlab建立计算力学课程的笔记和文件.zip

matlab建立计算力学课程的笔记和文件.zip
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

2. 通过python绘制y=e-xsin(2πx)图像

可以使用matplotlib库来绘制这个函数的图像。以下是一段示例代码: ```python import numpy as np import matplotlib.pyplot as plt def func(x): return np.exp(-x) * np.sin(2 * np.pi * x) x = np.linspace(0, 5, 500) y = func(x) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.title('y = e^{-x} sin(2πx)') plt.show() ``` 运行这段
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

实现实时监控告警系统:Kafka与Grafana整合

![实现实时监控告警系统:Kafka与Grafana整合](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9BVldpY3ladXVDbEZpY1pLWmw2bUVaWXFUcEdLT1VDdkxRSmQxZXB5R1lxaWNlUjA2c0hFek5Qc3FyRktudFF1VDMxQVl3QTRXV2lhSWFRMEFRc0I1cW1ZOGcvNjQw?x-oss-process=image/format,png) # 1.1 Kafka集群架构 Kafka集群由多个称为代理的服务器组成,这
recommend-type

导入numpy库,创建两个包含9个随机数的3*3的矩阵,将两个矩阵分别打印出来,计算两个数组的点积并打印出来。(random.randn()、dot()函数)

可以的,以下是代码实现: ```python import numpy as np # 创建两个包含9个随机数的3*3的矩阵 matrix1 = np.random.randn(3, 3) matrix2 = np.random.randn(3, 3) # 打印两个矩阵 print("Matrix 1:\n", matrix1) print("Matrix 2:\n", matrix2) # 计算两个数组的点积并打印出来 dot_product = np.dot(matrix1, matrix2) print("Dot product:\n", dot_product) ``` 希望