Overwriting rows with python

0

Someone who knows how ???? I share with you the code au revoir .

import csv

def leer():
    m1=open("archivo1.csv","rb")
    m1_csv=csv.reader(m1)
    var = ""

    for i,x in enumerate(m1_csv):

        lista0 = x[0:1]
        lista1 = x[1:2]
        header = str1 = ''.join(lista0)
        header1 = header[9:13]
        str1 = ''.join(lista1)
        str1 = str1[1:]
        str2 = str1[0:32]

        listas = []
        listas.append("The next header ")
        listas.append(header1)
        listas.append("")
        if(header1=="goin"):
            listas.remove("")
            listas.remove("goin")
            listas.append("error")    
            listas.append(" the hash is outdate: "+str2)        
        elif(header1=="omin"):
            listas.remove("")
            listas.remove("omin")
            listas.append("error")    
            listas.append(" the hash is outdate: "+str2)            
        elif( str2 == "074e3e3e82db7610dbeafd95c22d20a2"):
            listas.remove("")
            listas.append(" is using for speaking")
            listas.append(" example bla bla bla the packet")
            listas.append(" Incident: you can get powers")

        listo=["OUTGOING HEADERS"]
        listos=["INCOMING HEADERS"]

        m2_c=csv.writer(open("archivo2.csv","a"),lineterminator='\n')
        if(i==0):
            m2_c.writerow(listo)
        if(i==468):
            m2_c.writerow(listos)
        m2_c.writerow(listas)

    m1.close()

#escribir sin espacios
    
asked by Sergio Ramos 22.07.2016 в 22:03
source

1 answer

1

When you open the file for writing, the mode 'a' ( append ) only allows writing at the end of the file. To be able to "overwrite" you will have to add the + character to the mode, that is, a+ , a+b for binary files, as it seems that you use.

In summary, these are the combinations:

                  | r   r+   w   w+   a   a+
------------------|--------------------------
read              | +   +        +        +
write             |     +    +   +    +   +
create            |          +   +    +   +
truncate          |          +   +
position at start | +   +    +   +
position at end   |                   +   +

To move around the file, use the seek method, although it would be much better if you process everything in memory and save a file at the end of the process.

    
answered by 23.07.2016 / 14:39
source