2017-10-12 144 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()))