关于关闭xlsxwriter,我的python3脚本遇到了麻烦。我已经包含了workbook.close(),但这似乎导致了某种错误。有谁知道问题是什么?
import xlsxwriter
import statistics
workbook = xlsxwriter.Workbook('data.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': True})
power = []
for row in list:
power.append(row)
worksheet.write(i, col, row)
col += 1
worksheet.write(i, col, statistics.median(power))
workbook.close()
Traceback (most recent call last):
File "example.py", line 71, in <module>
workbook.close()
File "/usr/local/lib/python3.4/dist-packages/xlsxwriter/workbook.py", line 311, in close
self._store_workbook()
File "/usr/local/lib/python3.4/dist-packages/xlsxwriter/workbook.py", line 619, in _store_workbook
xml_files = packager._create_package()
File "/usr/local/lib/python3.4/dist-packages/xlsxwriter/packager.py", line 139, in _create_package
self._write_shared_strings_file()
File "/usr/local/lib/python3.4/dist-packages/xlsxwriter/packager.py", line 286, in _write_shared_strings_file
sst._assemble_xml_file()
File "/usr/local/lib/python3.4/dist-packages/xlsxwriter/sharedstrings.py", line 54, in _assemble_xml_file
self._write_sst_strings()
File "/usr/local/lib/python3.4/dist-packages/xlsxwriter/sharedstrings.py", line 84, in _write_sst_strings
self._write_si(string)
File "/usr/local/lib/python3.4/dist-packages/xlsxwriter/sharedstrings.py", line 96, in _write_si
string = re.sub('(_x[0-9a-fA-F]{4}_)', r'_x005F\1', string)
File "/usr/lib/python3.4/re.py", line 179, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: can't use a string pattern on a bytes-like object
答案 0 :(得分:0)
您需要使用.decode
将类似字节的对象转换为字符串,例如obj = response.read().decode('utf-8').
在您的情况下,列表中的对象必须是字节类型,将它们转换为字符串。
答案 1 :(得分:0)
我在示例中添加了一些变量初始化以使其编译,并且它似乎在Python 2和3上正确运行:
import xlsxwriter
import statistics
workbook = xlsxwriter.Workbook('data.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': True})
power = []
# I added these variables to the OP program.
list = [1, 2, 3, 4, 5]
i = 0
col = 0
for row in list:
power.append(row)
worksheet.write(i, col, row)
col += 1
worksheet.write(i, col, statistics.median(power))
workbook.close()
输出:
我猜这和你的例子之间的区别在于列表数组的内容。
您能否通过一个演示实际问题的示例来更新您的问题?