Python - writing and reading from a temporary file
<p>I am trying to create a temporary file that I write in some lines from another file and then make some objects from the data.  I am not sure how to find and open the temp file so I can read it.   My code:</p>

<pre><code>with tempfile.TemporaryFile() as tmp:
    lines = open(file1).readlines()
    tmp.writelines(lines[2:-1])

dependencyList = []

for line in tmp:
    groupId = textwrap.dedent(line.split(':')[0])
    artifactId = line.split(':')[1]
    version = line.split(':')[3]
    scope = str.strip(line.split(':')[4])
    dependencyObject = depenObj(groupId, artifactId, version, scope)
    dependencyList.append(dependencyObject)
tmp.close()
</code></pre>

<p>Essentially I just want to make a middleman temporary document to protect against accidentally overwriting a file. </p>

<p>As per the <a href="https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryFile" rel="nofollow">docs</a>, the file is deleted when the <code>TemporaryFile</code> is closed and that happens when you exit the <code>with</code> clause. So... don't exit the <code>with</code> clause. Rewind the file and do your work in the <code>with</code>. </p>

<pre><code>with tempfile.TemporaryFile() as tmp:
    lines = open(file1).readlines()
    tmp.writelines(lines[2:-1])
    tmp.seek(0)

    for line in tmp:
        groupId = textwrap.dedent(line.split(':')[0])
        artifactId = line.split(':')[1]
        version = line.split(':')[3]
        scope = str.strip(line.split(':')[4])
        dependencyObject = depenObj(groupId, artifactId, version, scope)
        dependencyList.append(dependencyObject)
</code></pre>

python temporary-files