如何更改.csv fi中行的最后一个值

2024-04-24 21:35:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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

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


Tags: 文件csvimportaddparser状态argparseargs
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()

我知道这是一个新的方式,但它的工作很好哈哈

你很接近,我查看了你的csv,因为你有一个标题行,我认为最好使用你的S.No作为唯一的taskid:

import pandas as pd
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-o', ' option', metavar='', help='-o <option> write either you want to add or view')

# Here I added the action="append"
parser.add_argument('-l', ' select', metavar='', help='-l <used to select the task for modification', action="append")
args = parser.parse_args()


def modify(filename, taskids):
    taskids = list(map(int, taskids))  # just to change from str to int for your taskids
    df = pd.read_csv(filename, sep=";")
    df.loc[df["S.No"].isin(taskids), "Status"] = "complete"
    df.to_csv(filename, sep=";", index=False)

modify("csv.csv", args.select)

我正在使用熊猫数据帧来简化它。df.loc[...]行用于选择命令行中给定的任务id中的每一行,并将Status列更改为“complete”。你知道吗

我还做了一个我认为您会感兴趣的小改动:我只是在解析器中为select选项添加了一个小的action="append"。这意味着您可以通过执行以下操作一次更改多个任务:

python todoarg.py -o modify -l 2 -l 6 -l 3

对于option参数,我建议您在解析器中使用choices参数:

parser.add_argument(
    "-o", " option",
    type    = str,
    choices = [
        "modify",
        "add",
        "cook_a_turkey"
    ],
    default = "modify",  # you can even use a default choice if the parameter is not given
    metavar = "",
    help    = "some help"
)

关于如何根据给option参数的值来选择要使用的方法,我认为我没有一个好的方法来做到这一点,但也许类似的方法可以工作:

my_methods = {
    "modify": modify,  # they keys are the same as provided in the choices in the argument parser
    "add": add_task,
    "cook_a_turkey": cook_that_turkey,
}
# And you can call the function like this: However you will have to change a bit your functions to parse the arguments in each of them.
my_methods[parser.option]("csv", args)

# For instance the modify will become:
def modify(filename, args):
    taskids = list(map(int, args.select))
    # ...
def add_task(filename, args):
    # do stuff
def cook_that_turkey(filename, args):
    # your grandma recipe

相关问题 更多 >