2012-02-15 23 views
6
  1. ¿Cómo comprobar que el archivo existe?
  2. ¿Cómo agregar un texto al archivo?

que sabe cómo crear el archivo, pero en este caso, se sobrescribe todos los datos:Agregar un texto al archivo en Python

import io 

with open('text.txt', 'w', encoding='utf-8') as file: 
    file.write('text!') 

En *nix puedo hacer algo como:

#!/bin/sh 

if [ -f text.txt ] 
    #If the file exists - append text 
    then echo 'text' >> text.txt; 

    #If the file doesn't exist - create it 
    else echo 'text' > text.txt; 
fi; 
+1

'abierto ('text.txt', 'a', encoding = 'UTF-8')' – kev

+1

Esto parece ser Python 3.x, ya que se utiliza el parámetro 'encoding' a' open() '. ¿Derecha? –

+0

¡Utilicé la búsqueda y no pude encontrar la respuesta! – tomas

Respuesta

15

Utilice el modo a vez de w para anexar al archivo:

with open('text.txt', 'a', encoding='utf-8') as file: 
    file.write('Spam and eggs!') 
+0

Gracias, no pude encontrar la clave '-a'. Dígale por favor, ¿cómo verificar que el archivo exista? – tomas

+1

¿Por qué quiere verificar si existe? ¿Lo anexas solo si aún no existe, lo cual no tiene sentido? – geoffspear

+0

@Wooble, solo quiero saber cómo hacerlo. Una de las soluciones para * nix: 'if os.path.exists (filename):' – tomas

0

En cuanto a su primera pregunta, Google buscará varias formas. Prueba esta pregunta anterior SO:

Pythonic way to test if a file exists?

+2

SO las respuestas deben ser autocontenidas, por lo tanto, proporcione la información más importante de la página enlazada en su respuesta - vea [Cómo responder] (http://stackoverflow.com/questions/how-to-answer) para más detalles. –

+0

¿Hay alguna manera de verificar un archivo sin 'os' (necesito la plataforma win/nux)? – tomas

+0

El módulo 'os' es portátil siempre que sea posible. 'os.path.isfile()' incluido – alexis

Cuestiones relacionadas