2010-05-27 7 views

Respuesta

66

Puede hacerlo de dos maneras:

f.write("text to write\n") 

o, dependiendo de la versión de Python (2 o 3):

print >>f, "text to write"   # Python 2.x 
print("text to write", file=f)  # Python 3.x 
+0

estoy usando f.writelines (str (x)) para escribir en un archivo donde x es la lista a decir ahora cómo escribir una lista x en un archivo de afrontamiento cada lista comienza en la nueva línea – kaushik

+1

@kaushik: f.write ('\ n'.join (x)) o f.writelines (i +' \ n 'para i en x) – Steven

+0

El ', file = f' es útil , gracias – nikhilvj

42

Tal vez ¿Se puede utilizar

file.write(your_string + '\n') 
+0

puedes usar el uso, por ejemplo, cuando escribes un int en un archivo, puedes usar *** file.write (str (a) + '\ n') *** –

14

Si utiliza de forma intensiva (una gran cantidad de líneas escritas), puede subclase 'archivo':

class cfile(file): 
    #subclass file to have a more convienient use of writeline 
    def __init__(self, name, mode = 'r'): 
     self = file.__init__(self, name, mode) 

    def wl(self, string): 
     self.writelines(string + '\n') 
     return None 

Ahora Ofrece una wl función adicional que hace lo que quiere:

fid = cfile('filename.txt', 'w') 
fid.wl('appends newline charachter') 
fid.wl('is written on a new line') 
fid.close() 

Tal vez me estoy perdiendo algo así como diferentes caracteres de nueva línea (\ n \ r, ...) o que º La última línea también termina con una nueva línea, pero funciona para mí.

0

Solo una nota, file no es compatible con Python 3 y se eliminó. Puede hacer lo mismo con la función integrada open.

f = open('test.txt', 'w') 
f.write('test\n') 
2

Solo necesita agregar el parámetro 'a'.

file_path = "/path/to/yourfile.txt" 
with open(file_path, 'a') as file: 
    file.write("This will be added to the next line\n") 

o

log_file = open('log.txt', 'a') 
log_file.write("This will be added to the next line\n") 
Cuestiones relacionadas