python - 如何更改 .csv 文件中一行的最后一个值
问题描述
我正在使用 CLI 创建一个待办事项列表,我想将一行的最后一个值(即状态)从“未完成”更改为“完成”
我知道我们不能像那样编辑 csv 文件,所以我们要做的是读取它更改值然后覆盖现有文件。这是 csv 文件:https ://drive.google.com/open?id=1fqc79mtVmZGZ_pb_2zrzDGVDmyMFWi6C 我试过这个:
import csv
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--option', metavar='', help='-o <option> write either you want to add or view')
parser.add_argument('-l', '--select', metavar='', help='-l <used to select the task for modification')
args = parser.parse_args()
def modify():
select = args.select
with open('csv.csv', 'r+', newline='') as file:
lines = list(file)
lines[int(select)][7] = 1
with open('csv.csv', 'w+', newline='') as ifile:
writer = csv.writer(ifile)
writer.writerows(lines)
当我们运行它时,我希望它:
python todoarg.py -o modify -l 2
它将第二行的状态从“未完成”更改为“完成”
解决方案
我也找到了一种不用熊猫的方法:
def modify():
with open("csv.csv", 'r+') as f:
lines = f.readlines()
f.seek(0)
task = args.select
for line in lines:
if not task in line.split(',')[0]:
f.write(line)
for line in lines:
if task in line.split(',')[0]:
#what we do here is print existing values using their index
#with split function and adding 'Complete' instead of
#6th index which was 'Incomplete'
f.write('\n' + line.split(',')[0] + ',' + line.split(',')[1] + ',' + line.split(',')[2] + ','
+ line.split(',')[3] + ',' + line.split(',')[4] + ','
+ line.split(',')[5] + ',' + 'Complete')
f.truncate()
我知道这是一种新方法,但效果很好,哈哈
推荐阅读
- azure-sql-database - Pyodbc Azure sql 数据库
- python - 如何让我的播放器与物体发生碰撞?
- kerberos - 如何访问 Ticket Granting Ticket?
- python - Python 2.7 和 Python 3.9 的结果完全不同
- git - 如何在保留特定分支和维护替换引用的同时从 git 存储库中删除死/大文件?
- python - 如何将 Pytorch 张量拆分为不同的维度?
- javascript - Braintree GraphQL - 将查询与 chargePaymentMethod 和 updateCustomer 突变相结合
- java - 谷歌云资源管理器V3 java客户端调用失败
- flutter - 如何跳转/隐藏第一个索引?颤动
- python - 在 Python 中使用 Lambda 函数、Map 和 Reduce 算法将两个矩阵相乘