Search code examples
pythontemporary-files

reading from a NamedTemporaryFile in python


I am creating a tempFile and then adding text to it by opening it with an editor(so that user can enter his message), and then save it to read the text from save NamedTemporaryFile.

with tempfile.NamedTemporaryFile(delete=False) as f:
    f.close()
    if subprocess.call([editor.split(" ")[0], f.name]) != 0:
        raise IOError("{} exited with code {}.".format(editor.split(" ")[0], rc))
    with open(f.name) as temp_file:
        temp_file.seek(0)
        for line in temp_file.readlines():
            print line

But every time it is coming out to be blank. why is it so ?


Solution

  • If you are using SublimeText as the editor, you will need to pass in the -w or --wait argument to make sure that the Python program waits until you actually close SublimeText again.

    Otherwise, you would just start to edit the file, and immediately try to read its contents which at that point are empty.

    You could also verify that, by putting in a print before reading the file.

    E.g.:

    editor = ['/path/to/sublime_text', '-w']
    
    with tempfile.NamedTemporaryFile(delete=False) as f:
        f.close()
        if subprocess.call(editor + [f.name]) != 0:
            raise IOError()
    
        # read file…