Charles Xavier
Charles Xavier

Reputation: 1045

Sorting CSV file and saving result as a CSV

I'd like to take a csv file, sort it and then save it as a csv. This is what I have so far and can't figure out how to write it to a csv file

import csv
with open('test.csv','r') as f:
    sample = csv.reader(f)
    sort = sorted(sample)

for eachline in sort:
     print (eachline)

Upvotes: 0

Views: 1325

Answers (2)

intedgar
intedgar

Reputation: 681

I think something like this should do the trick:

import pandas as pd
path = "C:/Your/file/path/file.csv"
df = pd.read_csv(path)
df = df.sort_values("variablename_by_which_to_sort", axis=0, ascending=True/False)
df.to_csv(path)

Upvotes: 0

mousetail
mousetail

Reputation: 8010

You don't need pandas for something simple like this:

# Read the input file and sort it
with open('input.csv') as f:
    data = sorted(csv.reader(f))
# write to the output file
with open('output.csv', 'w', newline='\n') as f:
    csv.writer(f).writerows(data)

Tuples in python sort lexicographically, meaning they sort by the first value, and if those are equal by the second. You can supply a key function to sorted to sort by a specific value.

Upvotes: 6

Related Questions