gpt4 book ai didi

python - 从 tempfile 创建和读取

转载 作者:IT老高 更新时间:2023-10-28 20:37:08 24 4
gpt4 key购买 nike

无论如何我可以写入临时文件并将其包含在命令中,然后关闭/删除它。我想执行命令,例如:some_command/tmp/some-temp-file.
非常感谢。

import tempfile
temp = tempfile.TemporaryFile()
temp.write('Some data')
command=(some_command temp.name)
temp.close()

最佳答案

完整示例。

import tempfile
with tempfile.NamedTemporaryFile() as temp:
temp.write('Some data')
if should_call_some_python_function_that_will_read_the_file():
temp.seek(0)
some_python_function(temp)
elif should_call_external_command():
temp.flush()
subprocess.call(["wc", temp.name])

更新:如评论中所述,这可能不适用于 Windows。使用this window 解决方案

更新 2:Python3 要求将要写入的字符串表示为字节,而不是 str,所以改为

temp.write(bytes('Some data', encoding = 'utf-8')) 

关于python - 从 tempfile 创建和读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5344287/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com