Python CSV: Can I do this with one 'with open' instead of two?
Question: I am a noobie.

I have written a couple of scripts to modify CSV files I work with.

The scripts:

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

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

    
    
    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)
    

My question is: Is there a more efficient way to do this?

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

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

Thanks for any help, it is greatly appreciated.

\--Luke


Answer: `csvfile` can be any object with a `write()` method. You could craft a custom
element, or use [StringIO](https://docs.python.org/2/library/stringio.html).
You'd have to verify efficiency yourself.

