【发布时间】:2021-11-26 00:50:51
【问题描述】:
我在一个文件中获得了一些示例数据 --> transactions1.csv transactions1
我需要编写一个无需使用 pandas 即可执行以下操作的函数:
- 打开文件
- 按升序对索引列进行排序
- 将更新后的数据保存回同一文件
这是我目前拥有的代码
import csv
def sort_index():
read_file=open("transactions1.csv","r")
r=csv.reader(read_file)
lines=list(r)
sorted_lines=sorted(lines[1:], key=lambda row: row[0])
read_file.close()
with open('transactions1.csv','w',newline='') as file_writer:
header=['Index','Day','Month','Year','Category','Amount','Notes'] #-
writer=csv.DictWriter(file_writer, fieldnames=header)
writer=csv.writer(file_writer)
writer.writerows(sorted_lines)
return False
sort_index()
当前输出:
1,2,Dec,2021,Transport,5,MRT cost
10,19,May,2020,Transport,25,taxi fare
2,5,May,2021,investment,7,bill
3,2,Aug,2020,Bills,8,small bill
4,15,Feb,2021,Bills,40,phone bill
5,14,Oct,2021,Shopping,100,shopping 20
6,27,May,2021,Others,20,other spend
7,19,Nov,2019,Investment,1000,new invest
8,28,Mar,2020,Food,4,drink
9,18,Nov,2019,Shopping,15,clothes
代码似乎不起作用,因为索引 10 出现在索引 1 之后。并且缺少标题。
预期输出:
Index,Day,Month,Year,Category,Amount,Notes
1,2,Dec,2021,Transport,5,MRT cost
10,19,May,2020,Transport,25,taxi fare
2,5,May,2021,investment,7,bill
3,2,Aug,2020,Bills,8,small bill
4,15,Feb,2021,Bills,40,phone bill
5,14,Oct,2021,Shopping,100,shopping 20
6,27,May,2021,Others,20,other spend
7,19,Nov,2019,Investment,1000,new invest
8,28,Mar,2020,Food,4,drink
9,18,Nov,2019,Shopping,15,clothes
【问题讨论】:
-
将其转换为 int(
int(row[0])而不是row[0])。现在您正在对字符串进行排序。 -
有没有办法让标题也显示在我的输出中?
-
可以,拨打
next(r),也不需要转list -
当我尝试 next(r) 时,我得到 ValueError: invalid literal for int() with base 10: 'D'