首页 > 解决方案 > 如何更改 .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

它将第二行的状态从“未完成”更改为“完成”

标签: pythonpython-3.xcsvargumentsargparse

解决方案


我也找到了一种不用熊猫的方法:

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

我知道这是一种新方法,但效果很好,哈哈


推荐阅读