如何使用tempfile模块从NamedTemporaryFile获取Python os.PathLike对象?
我试图使用需要文件对象列表的如何使用tempfile模块从NamedTemporaryFile获取Python os.PathLike对象?,python,Python,我试图使用需要文件对象列表的pdfkit库调用Python(3.8)函数。我只有字符串,所以我需要将每个字符串写入一个临时文件,在函数返回后将其删除。我可以为此推出我自己的解决方案,但是如果我可以使用tempfile模块来实现这一点,它将更加方便(和可移植)。不幸的是,当我用NamedTemporaryFile包装每个字符串时,我的函数会抱怨TypeError,我必须提供os.PathLike的内容,而不是临时文件包装器 是否可以从tempfile模块中获取适合此目的的内容 from tempf
pdfkit
库调用Python(3.8)函数。我只有字符串,所以我需要将每个字符串写入一个临时文件,在函数返回后将其删除。我可以为此推出我自己的解决方案,但是如果我可以使用tempfile模块来实现这一点,它将更加方便(和可移植)。不幸的是,当我用NamedTemporaryFile
包装每个字符串时,我的函数会抱怨TypeError
,我必须提供os.PathLike的内容,而不是临时文件包装器
是否可以从tempfile模块中获取适合此目的的内容
from tempfile import NamedTemporaryFile
import pdfkit
the_files = []
for html in my_html_strings:
tmp_file = NamedTemporaryFile(mode='w', suffix='.html')
tmp_file.write(html)
the_files.append(tmp_file)
pdf_data = pdfkit.from_file(the_files, False) # raises
和堆栈跟踪:
File "...", line 68, in my_code
pdf_data = pdfkit.from_file(section_files, False, options=opts)
File ".../lib/python3.8/site-packages/pdfkit/api.py", line 46, in from_file
r = PDFKit(input, 'file', options=options, toc=toc, cover=cover, css=css,
File ".../lib/python3.8/site-packages/pdfkit/pdfkit.py", line 41, in __init__
self.source = Source(url_or_file, type_)
File ".../lib/python3.8/site-packages/pdfkit/source.py", line 12, in __init__
self.checkFiles()
File ".../lib/python3.8/site-packages/pdfkit/source.py", line 28, in checkFiles
if not os.path.exists(path):
File "/usr/lib/python3.8/genericpath.py", line 19, in exists
os.stat(path)
TypeError: stat: path should be string, bytes, os.PathLike or integer, not _TemporaryFileWrapper
你不需要像我这样的人。您只需要一个表示文件路径的字符串。对于NamedTemporaryFile,该字符串是其
name
属性:
namedtempfile.name
几乎所有需要os.PathLike
的东西都应该使用普通字符串
如果出于某种奇怪的原因,您发现自己确实需要一个PathLike,而字符串实际上不起作用,您可以将该字符串包装成一个pathlib.Path
:
import pathlib
pathlike = pathlib.Path(nametempfile.name)
情况并非如此。您能发布完整的回溯吗