How can I create a tmp file in Python?

后端 未结 2 1410
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 06:15

I have this function that references the path of a file:

some_obj.file_name(FILE_PATH)

where FILE_PATH is a string of the path of a file, i

2条回答
  •  爱一瞬间的悲伤
    2020-12-01 06:45

    I think you're looking for this: http://docs.python.org/library/tempfile.html

    import tempfile
    with tempfile.NamedTemporaryFile() as tmp:
        print(tmp.name)
        tmp.write(...)
    

    But:

    Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).

    If that is a concern for you:

    import os, tempfile
    tmp = tempfile.NamedTemporaryFile(delete=False)
    try:
        print(tmp.name)
        tmp.write(...)
    finally:
        os.unlink(tmp.name)
        tmp.close()
    

提交回复
热议问题