Home > front end >  how to copy the row value as per row name into another row using pyhton
how to copy the row value as per row name into another row using pyhton

Time:05-10

Field_Name = ['Field Name', 'Success', 'Failure', '%']
thewriter = csv.DictWriter(f, fieldnames=Field_Name)
# thewriter.writeheader()
thewriter.writerow({'Field Name': 'Extraction Accuracy', '%': extraction_accuracy})
thewriter.writerow({'Field Name': 'Classification Accuracy', '%': " "})

i want to copy "DOC-TYPE", % row value into "Classification Accuracy"

enter image description here

CodePudding user response:

Something like this would work.

  • You just read the original data from the file.
  • extract the value from the DOC-Type row
  • insert value into the Classification Accuracy row
  • write the data back to same file
from csv import DictReader, DictWriter

with open(csvfile) as csvf:  
    reader = csv.DictReader(csvf)  # read data from csv file
    for row in reader:
        # find "DOC-TYPE" row and get value of "%"
        if row["Field Name"] == "DOC-TYPE":
            value = row["%"]  # assign value to `value`
            break
    # find "Classif.. Acc.." row and set the "%" key's value to `value`
    for row in reader:
        if row["Field Name"] == "Classification Accuracy":
            row["%"] = value  # copy value into this cell
            break


# then you would just write back to the same file
Field_Name = ['Field Name', 'Success', 'Failure', '%']
with open(csvfile, 'wt') as csvf:
    writer = csv.DictWriter(csvf, fieldnames=Field_Name)
    for row in reader:
        writer.writerow(row)

For further info on the csv.DictReader see the python docs https://docs.python.org/3/library/csv.html?highlight=csv#csv.DictReader

CodePudding user response:

Unfortunately, you have to read the file and get the row pf DOC-TYPE. When you found the row you can extract the value and paste it to your new row. I am not aware of any other way to get the row by the first entry, than reading through the file until you found it by your own.

CodePudding user response:

If your current rows are fixed in space (that is, immutable in order), you can do the follwing:

list_read = csv.reader(f)
current_list = list(list_read)
desired_value = current_list[13][-1]
# Or it could be current_list[-3][-1] if all the rows depicted finish until 15

Finally, proceed to use:

thewriter.writerow({'Field Name': 'Classification Accuracy', '%': desired_value })

Hope that this could be of use :)

  • Related