简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM