Python Forum
CSV file column swapping
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
CSV file column swapping
#1
Hello, I am trying to swap the values in columns 1 and 2 respectively from an input file (.csv) and have them displayed swapped in the output file (the other columns are still the same). Any help would be appreciated. For this assignment, I'm not allowed to use Pandas.

This is my current code:
def re_order(in_file, out_file):
    with open(in_file, 'r', newline='') as in_file_handle:
        reader = csv.reader(in_file_handle)
        columns = [1, 0]
        for row in reader:
            content = [row[i] for i in columns]
        with open(out_file, 'w', newline='') as out_file_handle:
            writer = csv.writer(out_file_handle)
            writer.writerow(content)
Reply


Messages In This Thread
CSV file column swapping - by DJPunk - Mar-04-2019, 02:41 AM
RE: CSV file column swapping - by ichabod801 - Mar-04-2019, 02:46 AM
RE: CSV file column swapping - by DJPunk - Mar-04-2019, 02:56 AM
RE: CSV file column swapping - by ichabod801 - Mar-04-2019, 03:01 AM
RE: CSV file column swapping - by DJPunk - Mar-04-2019, 03:10 AM
RE: CSV file column swapping - by DJPunk - Mar-04-2019, 04:11 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  To extract a specific column from csv file and compute the average vicson 2 8,136 Oct-20-2018, 03:18 AM
Last Post: vicson

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020