且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将列从一个 csv 文件复制到另一个 csv 文件?

更新时间:2023-01-30 19:28:08

  • t.csv
编号,天5、周一4、周二3、周三2,周四

  • 脚本
使用 open('t.csv','r') 作为文件:f=csv.reader(文件)数据=[]对于 f 中的行:数据.附加(行)标题=数据[0]行=数据[1:]行.排序(反向=假)使用 open('t_out.csv','w',newline='') 作为 file_out:f=csv.writer(file_out)f.writerow(标题)f.writerows(行)

  • t_out.csv
编号,天2,周四3、周三4、周二5、周一

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