switch variable and write problems,python
<pre><code>import csv
import sys 
def switch():
    file1=open('enjoysport.csv','r')
    for line in file1:
        line.split(",")[0],line.split(",")[-1]=line.split(",")[-1],line.split(",")[0]
    file1.close()                                       
    origin=sys.stdout
    fil2=open("test.csv","w")
    sys.stdout=fil2
    print(file1)
    sys.stdout = origin                  
    fil2.close()
switch()
</code></pre>

<p>I want to switch the first column and last column ,but it didn't work,what's more,the file after switching cannot be written into the new csv.file?</p>

<p>like this:</p>

<pre><code>&lt;_io.TextIOWrapper name='agaricus_lepiota.csv' mode='r' encoding='cp1252'&gt;
</code></pre>

<p>what's wrong?Thank you in advance:)</p>

<p>You need to actually write the updated row to the file, you can also use the <em>csv</em> lib to read and write your file content:</p>

<pre><code>def switch():
    with open('enjoysport.csv') as f,  open("test.csv", "w") as out:
        wr = csv.writer(out)
        for row in csv.reader(f):
            row[0], row[-1] = row[-1], row[0]
            wr.writerow(row) # actually write it to test.csv
</code></pre>

<p>In your own code all you are doing is shifting elements in each row, you never write the result so it is a pointless exercise. </p>

<p>Why you see <code>&lt;_io.TextIOWrapper name='agaricus_lepiota.csv' mode='r' encoding='cp1252'&gt;</code> is because <code>sys.stdout = fil2</code> <em>redirects stdout</em> to <em>file2</em>, then you print the reference to the <code>file1</code> i.e the file object so that gets written/redirected to your file.</p>

python output