Python CSV: Can I do this with one 'with open' instead of two?
<p>I am a noobie.</p>

<p>I have written a couple of scripts to modify CSV files I work with.</p>

<p>The scripts:</p>

<p>1.) change the headers of a CSV file then save that to a new CSV file,.</p>

<p>2.) Load that CSV File, and change the order of select columns using DictWriter.</p>

<pre><code>from tkinter import *
from tkinter import filedialog
import os
import csv

root = Tk()
fileName = filedialog.askopenfilename(filetypes=(("Nimble CSV files", "*.csv"),("All files", "*.*")))
outputFileName = os.path.splitext(fileName)[0] + "_deleteme.csv" #my temp file
forUpload = os.path.splitext(fileName)[0] + "_forupload.csv"

#Open the file - change the header then save the file
with open(fileName, 'r', newline='') as infile, open(outputFileName, 'w',    newline='') as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile, delimiter=',', lineterminator='\n')

    row1 = next(reader)

    #new header names
    row1[0] = 'firstname'
    row1[1] = 'lastname'
    row1[4] = 'phone'
    row1[5] = 'email'
    row1[11] = 'address'
    row1[21] = 'website'

    #write the temporary CSV file
    writer.writerow(row1)
    for row in reader:
        writer.writerow(row)

#Open the temporary CSV file - rearrange some columns
with open(outputFileName, 'r', newline='') as dInFile, open(forUpload, 'w', newline='') as dOutFile:
    fieldnames = ['email', 'title', 'firstname', 'lastname', 'company',   'phone', 'website', 'address', 'twitter']
    dWriter = csv.DictWriter(dOutFile, restval='', extrasaction='ignore',   fieldnames=fieldnames, lineterminator='\n')
    dWriter.writeheader()

    for row in csv.DictReader(dInFile):
        dWriter.writerow(row)
</code></pre>

<p>My question is: Is there a more efficient way to do this? </p>

<p>It seems like I shouldn't have to make a temporary CSV file ("_deleteme.csv") I then delete.</p>

<p>I assume making the temporary CSV file is a rookie move -- is there a way to do this all with one 'With open' statement?</p>

<p>Thanks for any help, it is greatly appreciated. </p>

<p>--Luke</p>

<p><code>csvfile</code> can be any object with a <code>write()</code> method.  You could craft a custom element, or use <a href="https://docs.python.org/2/library/stringio.html" rel="nofollow">StringIO</a>.  You'd have to verify efficiency yourself.</p>

python csv dictionary header temporary-files