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
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.
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.
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.
You can use:
f.write(str(i) + '\n')
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With