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>The problem is with this line</p>

<pre><code>    line.split(",")[0],line.split(",")[-1]=line.split(",")[-1],line.split(",")[0]
</code></pre>

<p>You create four temporary lists by split, which are discarded after that line directly because they are not assigned to any variable.</p>

<p>You have to process one line and write it directly to the new file:</p>

<pre><code>file1=open('enjoysport.csv','r')
fil2=open("test.csv","w")
for line in file1:
    parts = line.rstrip().split(',')
    parts[0],parts[-1] = parts[-1], parts[0]
    file2.write(','.join(parts) + '\n')
file1.close()
file2.close()
</code></pre>

python output