switch variable and write problems,python
Question: 
    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()
    

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?

like this:

    
    
    <_io.TextIOWrapper name='agaricus_lepiota.csv' mode='r' encoding='cp1252'>
    

what's wrong?Thank you in advance:)


Answer: You need to actually write the updated row to the file, you can also use the
_csv_ lib to read and write your file content:

    
    
    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
    

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.

Why you see `<_io.TextIOWrapper name='agaricus_lepiota.csv' mode='r'
encoding='cp1252'>` is because `sys.stdout = fil2` _redirects stdout_ to
_file2_ , then you print the reference to the `file1` i.e the file object so
that gets written/redirected to your file.

