How can I create a tmp file in Python?

后端 未结 2 1396
隐瞒了意图╮
隐瞒了意图╮ 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:35

    There is a tempfile module for python, but a simple file creation also does the trick:

    new_file = open("path/to/FILE_NAME.ext", "w")
    

    Now you can write to it using the write method:

    new_file.write('this is some content')
    

    With the tempfile module this might look like this:

    import tempfile
    
    new_file, filename = tempfile.mkstemp()
    
    print(filename)
    
    os.write(new_file, "this is some content")
    os.close(new_file)
    

    With mkstemp you are responsible for deleting the file after you are done with it. With other arguments, you can influence the directory and name of the file.


    UPDATE

    As rightfully pointed out by Emmet Speer, there are security considerations when using mkstemp, as the client code is responsible for closing/cleaning up the created file. A better way to handle it is the following snippet (as taken from the link):

    import os
    import tempfile
    
    fd, path = tempfile.mkstemp()
    try:
        with os.fdopen(fd, 'w') as tmp:
            # do stuff with temp file
            tmp.write('stuff')
    finally:
        os.remove(path)
    

    The os.fdopen wraps the file descriptor in a Python file object, that closes automatically when the with exits. The call to os.remove deletes the file when no longer needed.

    0 讨论(0)
  • 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()
    
    0 讨论(0)
提交回复
热议问题