Quiero:¿Cómo se abre (lectura-escritura) o se crea un archivo con truncamiento permitido?
- abrir un archivo en modo lectura-escritura si existe;
- créelo si no existe;
- ser capaz de truncar en cualquier momento y en cualquier lugar.
EDITAR: con truncado me refiero a escribir hasta una posición y desechar el resto del archivo, si está presente
Todo esto atómicamente (con un solo open()
llamada o la simulación de una sola open()
llamada)
sin sola modalidad abierta parece aplicarse:
- r: es evidente que no funciona;
- r +: falla si el archivo no existe;
- w: recrear el archivo si existe;
- w +: vuelve a crear el archivo si existe;
- a: no se puede leer;
- a +: no se puede truncar.
Algunas combinaciones que probé (rw, rw +, r + w, etc.) parece que no funcionan. ¿Es posible?
Algunos doc de Rubí (se aplica a pitón también):
r
Read-only mode. The file pointer is placed at the beginning of the file.
This is the default mode.
r+
Read-write mode. The file pointer will be at the beginning of the file.
w
Write-only mode. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.
w+
Read-write mode. Overwrites the existing file if the file exists. If the
file does not exist, creates a new file for reading and writing.
a
Write-only mode. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist,
it creates a new file for writing.
a+
Read and write mode. The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
Así que básicamente quiere sobrescribir una archivo y asegúrese de que los contenidos anteriores no se mantengan por debajo del punto en que dejó de escribir? –
Sí. 'file.truncate()' funciona para este propósito y funciona cuando el archivo es "r +", "w", "w +". Pero todos tienen los defectos que enumeré arriba. – ceztko