xlwt 库使用时Attempt to overwrite cell: sheetname='Sheet1' rowx=0 colx=0将overwrite设置为True
时间: 2024-02-27 12:57:27 浏览: 208
是的,如果你正在使用 xlwt 库写入 Excel 文件,你可以将 overwrite 参数设置为 True,以允许在同一个单元格上写入多次数据。在 xlwt 库中,你可以通过设置 Workbook 对象的 cell_overwrite_ok 属性来实现这个功能。示例代码如下:
```python
import xlwt
# 创建 Workbook 对象
workbook = xlwt.Workbook()
# 添加工作表
worksheet = workbook.add_sheet('Sheet1')
# 设置 cell_overwrite_ok 属性
worksheet.cell_overwrite_ok = True
# 写入数据
worksheet.write(0, 0, 'Hello')
worksheet.write(0, 0, 'World')
# 保存文件
workbook.save('example.xls')
```
在这个例子中,我们将 cell_overwrite_ok 属性设置为 True,允许在同一个单元格上写入多次数据。在写入数据时,我们首先写入 'Hello',然后再次写入 'World',覆盖了原有的数据。最后,我们保存 Excel 文件,并命名为 example.xls。
相关问题
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()`语句更加规范和安全地处理路径和文件操作。
#模块导入 from selenium import webdriver from time import sleep from lxml import etree import xlwt import openpyxl #初始化 ##浏览器部分 bro = webdriver.Chrome() bro.get("https://china.nba.cn/players/stats/#!/stephen_curry") page_text = bro.page_source sleep(5) bro.quit() tree=etree.HTML(page_text) ##表格数据部分 file=xlwt.Workbook() sheet1 = file.add_sheet('sheet1',cell_overwrite_ok=True) line_per=[] #数据爬取函数准备 def score_record(x): tree_line=tree.xpath(x) line_0=[] for i in tree_line: tree_line_word=i.xpath('.//text()') for i in tree_line_word: if i.strip(): line_0.append(i.strip()) line_true=[line_0[0],line_0[18],line_0[19],line_0[20],line_0[21],line_0[22],line_0[23]] line_per.append(line_true) #爬取数据 a='/html/body/div[5]/div/div/div/div[2]/div[2]/section/div/div[2]/div[2]/div[1]/div[1]/div[3]/nba-stat-table/div/div[1]/table/thead/tr' score_record(a) for i in range(1,14): webside='/html/body/div[5]/div/div/div/div[2]/div[2]/section/div/div[2]/div[2]/div[1]/div[1]/div[3]/nba-stat-table/div/div[1]/table/tbody/tr[{}]'.format(i) score_record(webside) #保存数据 file = xlwt.Workbook() sheet1 = file.add_sheet('sheet1',cell_overwrite_ok=True) for j in range(0,14): for i in range(0,7): sheet1.write(j,i,line_per[j][i]) file.save('python结课程序.xls') #分析数据 sheet1.write(0,7,"两分出手") sheet1.write(0,8,"两分命中") wb = openpyxl.load_workbook('python结课程序.xls') sheet = wb['sheet1'] for i in range(2, 15): c_val = sheet.cell(row=i, column=3).value e_val = sheet.cell(row=i, column=5).value g_val = sheet.cell(row=i, column=7).value result = c_val - e_val - g_val sheet.cell(row=i, column=8).value = result for i in range(2, 15): b_val = sheet.cell(row=i, column=2).value d_val = sheet.cell(row=i, column=4).value f_val = sheet.cell(row=i, column=6).value result = b_val - d_val - f_val sheet.cell(row=i, column=9).value = result wb.save('python结课程序.xls')
这是一个使用 Python 爬取 NBA 球员数据并进行简单分析的程序。其中使用了 Selenium、lxml、xlwt 和 openpyxl 等模块,主要流程为:
1. 使用 Selenium 模拟浏览器访问 NBA 官网的球员数据页面并获取页面源代码。
2. 使用 lxml 对页面源代码进行解析,提取出需要的表格数据。
3. 将数据保存到一个二维数组中。
4. 使用 xlwt 将数据写入 Excel 文件中。
5. 使用 openpyxl 读取 Excel 文件并对数据进行简单分析,计算出两分出手数和两分命中数,并将结果写入 Excel 文件中。
该程序的功能比较简单,但是涉及到了多个 Python 库的使用,可以作为初学者学习 Python 爬虫和数据分析的一个参考。
阅读全文
相关推荐

















