簡體   English   中英

如何更改.csv文件中一行的最后一個值

[英]How to change the last value of a row in .csv file

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

我知道這是一種新穎的方法,但是效果很好

您接近了,我查看了您的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)

我正在使用Pandas數據框來簡化它。 df.loc[...]行用於選擇每一行,其中S.No是您在命令行中給定的任務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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM