Home > Blockchain >  Sorting CSV file and saving result as a CSV
Sorting CSV file and saving result as a CSV

Time:11-08

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)

CodePudding user response:

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.

CodePudding user response:

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)
  • Related