Priyx
Priyx

Reputation: 73

How to copy columns from one csv file to another csv file?

I have input.csv file with below format

number day
5      Mon
4      Tue
3      Wed
2      Thu

and I want to copy this data to another output.csv file with reverse order

number day
2      Thu
3      Wed
4      Tue
5      Mon

I have written this code but don't know how to proceed with reverse thing

cols = ["number", "day"]
file_path = "input.csv"
pd.read_csv(file_path, usecols=cols).to_csv("output.csv", index=False)

Upvotes: 1

Views: 1080

Answers (1)

DevScheffer
DevScheffer

Reputation: 499

  • t.csv
number,day
5,Mon
4,Tue
3,Wed
2,Thu
  • script

with open('t.csv','r') as file:
    f=csv.reader(file)
    data=[]
    for row in f:
        data.append(row)
    header=data[0]
    rows=data[1:]
    rows.sort(reverse=False)

with open('t_out.csv','w',newline='') as file_out:
    f=csv.writer(file_out)
    f.writerow(header)
    f.writerows(rows)


  • t_out.csv
number,day
2,Thu
3,Wed
4,Tue
5,Mon

Upvotes: 2

Related Questions