2012-07-13 14 views
9

Tengo el siguiente código:Python reemplazar y sobrescribir en lugar de añadir

import re 
#open the xml file for reading: 
file = open('path/test.xml','r+') 
#convert to string: 
data = file.read() 
file.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data)) 
file.close() 

donde me gustaría para reemplazar el contenido de edad que está en el archivo con el nuevo contenido. Sin embargo, cuando ejecuto mi código, se agrega el archivo "test.xml", es decir, tengo el contenido anterior seguido por el nuevo contenido "reemplazado". ¿Qué puedo hacer para eliminar las cosas viejas y solo guardar las nuevas?

+1

http://stackoverflow.com/questions/2424000/read-and-overwrite-a -file-in-python –

Respuesta

20

Es necesario utilizar truncar si usted quiere hacer en lugar de reemplazar: http://docs.python.org/library/stdtypes.html?highlight=truncate#file.truncate

O utiliza open(myfile, 'w'). Esto eliminará el archivo anterior y creará uno nuevo.

AFAIK truncado no cambia el inodo, pero abierto (..., 'w') creará un nuevo inodo. Pero en la mayoría de los casos esto no importa. ... Lo probé ahora. Tanto open (..., 'w') como truncate() no cambian el número de inodo del archivo. (Probado con Ubuntu 12.04 NFS y ext4).

Por cierto, esto no está realmente relacionado con Python. El intérprete llama a la API de bajo nivel correspondiente. El método truncate() funciona de la misma en el lenguaje de programación C: Ver http://man7.org/linux/man-pages/man2/truncate.2.html

+0

Genial, el truncado funcionó. ¡Gracias! – Kaly

0

Usando truncate(), la solución podría ser

import re 
#open the xml file for reading: 
with open('path/test.xml','r+') as f: 
    #convert to string: 
    data = f.read() 
    f.seek(0) 
    f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data)) 
    f.truncate() 
    f.close() 
Cuestiones relacionadas