2017-10-12 85 views
1

我发现使用pandashere将生成的表格导出为PDF格式的相当不错的方法,但将其转换为PNG文件的部分对我来说是无趣的。将pandas表格导出为pdf

的问题是,我得到了以下错误消息:

--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-10-9818a71c26bb> in <module>() 
    13 
    14 with open(filename, 'wb') as f: 
---> 15  f.write(template.format(z.to_latex())) 
    16 
    17 subprocess.call(['pdflatex', filename]) 

TypeError: a bytes-like object is required, not 'str' 

我真的不理解摆在首位,这使得它非常难以纠正错误的代码。我的代码如下所示:

import subprocess 

filename = 'out.tex' 
pdffile = 'out.pdf' 

template = r'''\documentclass[preview]{{standalone}} 
\usepackage{{booktabs}} 
\begin{{document}} 
{} 
\end{{document}} 
''' 

with open(filename, 'wb') as f: 
    f.write(template.format(z.to_latex())) 

subprocess.call(['pdflatex', filename]) 

其中zpandas产生DataFrame

希望有人可以帮忙。 预先感谢您, Sito。

回答

0

问题是,你打开一个文件以字节模式写入 - 这就是“b”字符在拨打open()时的含义 - 然后传递字符串数据。更改此:

with open(filename, 'wb') as f: 
    f.write(template.format(z.to_latex())) 

这样:

with open(filename, 'w') as f: 
    f.write(template.format(z.to_latex()))