Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing text file with line breaks

I want to write a text file where many lines are created, so I want to know how to put each value on a new line.

this is my code:

import itertools
from itertools import permutations , combinations
lista=[]

splits=itertools.permutations('0123456789', 5)
for x in splits:
    lista.append(x)

f=open('lala.txt', 'w')
for i in lista:
    f.write(str(i))

in this part I need to put the line break: f.write(str(i))

I have tried with: f.write(str(i)\n) but gives me an error

like image 298
user1770096 Avatar asked Oct 24 '12 03:10

user1770096


People also ask

How do you put a line break in a text file?

There is carriage return with the escape sequence \r with hexadecimal code value 0D abbreviated with CR and line-feed with the escape sequence \n with hexadecimal code value 0A abbreviated with LF. Text files on MS-DOS/Windows use CR+LF as newline. Text files on Unix/Linux/MAC (since OS X) use just LF as newline.

How do you add a line break to a text file in Python?

In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line.

How do you add a line break in a text file in Java?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.


3 Answers

You can use:

f.write(str(i) + '\n')

like image 118
wim Avatar answered Oct 28 '22 13:10

wim


Since your lines are already in a list, you can use writelines():

import itertools

lista = [",".join(i)+'\n' for i in itertools.permutations('0123456789',5)]

with open('lala.txt', 'w') as f:
    f.writelines(lista)

I've used the with statement which will automatically close the file for you; and used a list comprehension to create your initial list of permutations.

like image 41
Burhan Khalid Avatar answered Oct 28 '22 12:10

Burhan Khalid


Editing the list itself might be undesirable. In such cases, you could csv module:

import itertools, os, csv

lista = list(itertools.permutations('0123456789',5))

with open('lala.txt', 'w', newline=os.linesep) as f:
    writer = csv.writer(f, quoting=csv.QUOTE_NONE)
    writer.writerows(lista)

The quoting=csv.QUOTE_NONE is to remove the " marks presented because the permuted items are strings.

like image 32
Baumann Avatar answered Oct 28 '22 12:10

Baumann