Home > Enterprise >  How to rewrite only one frame (line[2]) in line in .csv file?
How to rewrite only one frame (line[2]) in line in .csv file?

Time:10-28

I would like to rewrite value in csv file only in third frame for every line. First two frames would be same.

But in output of this code is

builtins.TypeError: '_csv.writer' object is not iterable

import csv

with open('friends.csv', mode='w') as file: 
    writer = csv.writer(file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
   
new_age = "25"

for line in writer:
    writer.writerow(['line[0]','line[1]',new_age]) #it means that first two frmaes will be rewrited for same value like they are, last one will be rewrited to new_age.

Do you know how makes it better?

Thank you

CodePudding user response:

A csv file is a text file. That means that the blessed way to change it is to write a different file and rename the new file with the original name in the end:

# open the files
with open('friends.csv', mode='r') as oldfile, open(
        'friends.tmp', mode='w', newline='') as newfile:
    # define a reader and a writer
    reader = csv.reader(oldfile, delimiter=';', quotechar='"')
    writer = csv.writer(newfile, delimiter=';', quotechar='"',
                        quoting=csv.QUOTE_MINIMAL)
    # copy everything changing the third field
    for row in reader:
        writer.writerow([row[0], row[1], ,new_age])
# ok, time to rename the file
os.replace('friends.tmp', 'friends.csv')

CodePudding user response:

I think you need to Define your CSV file CSV_File = 'friends.csv

then call with open(CSV_file,'wb') as file: and you need to remove the quotes surrounding your line[1] line[0]

to skip first two lines open outfile with mode wb instead of w

CodePudding user response:

Have a look at convtools library, which provides both a csv helper and a lot of data processing primitives.

from convtools import conversion as c
from convtools.contrib.tables import Table

# if there's header and "age" is the column name
Table.from_csv("friends.csv", header=True).update(
    age=25
    # to reduce current ages you could:
    # age=c.col("age").as_type(int) - 10
).into_csv("processed_friends.csv")

# if there's no header and a column to rewrite is the 2nd one
Table.from_csv("friends.csv").update(COLUMN_1=25).into_csv(
    "friends_processed.csv", include_header=False
)

# if replacing the current file is absolutely needed
rows = list(
    Table.from_csv("friends.csv", header=True)
    .update(age=25)
    .into_iter_rows(list, include_header=True)
)
Table.from_rows(rows).into_csv("friends.csv", include_header=False)

  • Related