Escribir cadena en un archivo en una línea nueva cada vez


Quiero añadir una nueva línea a mi cadena cada vez que llame a file.write(). ¿Cuál es la forma más fácil de hacer esto en Python?

Author: alex, 2010-05-27

7 answers

Use "\n":

file.write("My String\n")

Vea el manual de Python para referencia.

 171
Author: halfdan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-24 20:00:08

Puedes hacer esto de dos maneras:

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

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

print >>f, "text to write"         # Python 2.x
print("text to write", file=f)     # Python 3.x
 79
Author: Greg Hewgill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-27 03:58:56

Puedes usar:

file.write(your_string + '\n')
 53
Author: Krishna K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-12 16:19:04

Si lo usas extensivamente (muchas líneas escritas), puedes subclase'file':

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 función adicional wl que hace lo que quieres:

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

Tal vez me falta algo 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í.

 16
Author: mathause,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-12 12:02:35
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")
 2
Author: Panos Kal.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-05 08:20:48

Esta es la solución que se me ocurrió tratando de resolver este problema por mí mismo con el fin de producir sistemáticamente \n's como separadores. Escribe usando una lista de cadenas donde cada cadena es una línea del archivo, sin embargo, parece que puede funcionar para usted también. (Python 3.+)

#Takes a list of strings and prints it to a file.
def writeFile(file, strList):
    line = 0
    lines = []
    while line < len(strList):
        lines.append(cheekyNew(line) + strList[line])
        line += 1
    file = open(file, "w")
    file.writelines(lines)
    file.close()

#Returns "\n" if the int entered isn't zero, otherwise "".
def cheekyNew(line):
    if line != 0:
        return "\n"
    return ""
 1
Author: democidist,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-11 22:16:28

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

f = open('test.txt', 'w')
f.write('test\n')
 0
Author: user1767754,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-21 09:00:37