2

I have looked around but didnt quite find what i have problems with.

The question i have about is that in the csv files called registro_usuarios.csv that has the following data. Which has 6 rows and 6 colmuns

registro_usuarios.csv:
RUT,Name,LastName,E-mail,ISBN1,ISBN2
111,Pablo1,Alar1,mail1,0,0
222,Pablo2,Alar2,mail2,0,0
333,Pablo3,Alar3,mail3,0,0
444,Pablo4,Alar4,mail4,0,0
555,Pablo5,Alar5,mail5,0,0

Now how do can i make a def that allows me to replace a 0 below ISBN1 or ISBN2 for a given RUT?... For example, i want to replace the ISBN1 of the rut 333 for 777. Then after using the def, it should change the data in the csv like this. since rows and columns starts with 0,0 i believe then ISBN1 of the rut 333 is row 3 column 5 if im not mistaken.

registro_usuarios.csv:
RUT,Nombre,Apellido,E-mail,ISBN1,ISBN2
111,Pablo1,Alar1,mail1,0,0
222,Pablo2,Alar2,mail2,0,0
333,Pablo3,Alar3,mail3,777,0
444,Pablo4,Alar4,mail4,0,0
555,Pablo5,Alar5,mail5,0,0

2 Answers 2

1

This is the simplest way I could think of:

>>> import csv
>>> with open('data.csv') as f:
...      data = [r for r in csv.reader(f)]
... 
>>> data[3][4] = '777'
>>> with open('data.csv', 'w') as f:
...     csv.writer(f).writerows(data)
...

As you mentioned you want to alter a row with an specific RUT. In that case I would use DictReader/DictWriter and a function to change the row based on the RUT:

import csv

def change_by_rut(csv_data, rut, new_isbn1):
    for row in csv_data:
        if row['RUT'] == rut:
            row['ISBN1'] = new_isbn1

with open('data.csv') as f:
    data = [r for r in csv.DictReader(f)]

change_by_rut(data, '333', '777')

with open('data.csv', 'w') as f:
    writer_obj = csv.DictWriter(f, fieldnames=data[0].keys())

    writer_obj.writeheader()
    writer_obj.writerows(data)
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, this has given me something to use. I will now try and make the code.
0

You could use pandas too:

# recreate file
from pathlib import Path

Path('temp.txt').write_text("""RUT,Name,LastName,E-mail,ISBN1,ISBN2
111,Pablo1,Alar1,mail1,0,0
222,Pablo2,Alar2,mail2,0,0
333,Pablo3,Alar3,mail3,0,0
444,Pablo4,Alar4,mail4,0,0
555,Pablo5,Alar5,mail5,0,0""")

import pandas as pd
df = pd.read_csv('temp.txt', index_col=0)
df.loc[333,'ISBN1'] = 777
print(df)
# export example
df.to_csv('temp2.txt')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.