lot = [('Apples', '=', 10),
('Oranges', '<', 20),
('Peaches','(Florida)','No stock')]
with open('tototo.txt','w') as f:
f.write( '\n'.join(' '.join(str(x) for x in tu) for tu in lot) )
Creating the entire text before writing it makes the writing in one pass.
Provided that the text isn't 25 GB long....
Note that on Windows, if the mode is 'w'
, the OS will write \r\n each time it must write a \n;
If you want just \n to be written, you must define the mode as 'rb'
PS
It is 'wb'
, not rb'
Edit 1
When Python writes on disk in 'w'
mode on Windows, the operating system Windows writes \r\n sequences as ends of lines when it has lines to write on a disk, and when it has to write strings containing newlines, whatever are these newlines, \n alone or \r\n
If, for any personal whim, or curiosity, or religious conviction, or as a symptom of somnambulism, or to impress your wife, or to please your capricious kid, or because of a psychopath ghost living in your computer and shrieking each time an orthodox \r\n newline is written on disk, or simply because your algorithm requires it ...... yes, it may happen that you want to write only a newline as \n on a disk.... that's not science-fiction, it may REALLY happen, you now..... it happened to me, yes believe me or not , I was faced to the fact I was obliged to write a \n alone on a disk on Windows, without any nihil obstat and complementary imprimatur from some pythonist pope ! .... well, yes it may happen, and then, after having locked your seat-belt, you CAN, yes we can, write a newline \n on a disk on Windows ! Yes yes yes, it is possible and not a cause of damnation
Then , only in one of these cases, and if you have the legal age and all your mental capacities, and having drunk no beer nor wine in excess, you can use 'wb'
to write newlines \n alone on a disk on Windows.
But THAT'S NOT MANDATORY ! You remain free to do so or not
.
Another thing is that when Python reads files in 'r'
mode, the Universal Newline Support (see PEP 278) is enabled by default: it consists in the fact that all types of newlines found by Python in a file are transformed into the single character \n.
But it may also happen that you need to read a file without any transformation of newlines. In this case, instead of disabling the Universal Newline Support, you can read a particular file in mode 'rb'
But you are NOT OBLIGED and I don't incite anybody to do so or the contrary. You do what you want, all that ridiculous stuff is to explain something useful to know.
.
Edit 2
I had tried to use writelines(), but I hadn't thought to use % formating to add a newline with sipmplicity .
Now that I've seen Derek Litz's answer, I have an evident solution:
lot = [('Apples', '=', 10),
('Nuts', '<', 20),
('Peaches','(Florida)','No stock')]
with open('tototo.txt','w') as f:
f.writelines( '%s %s %s\n' % tu for tu in lot )
Only if length of the tuples is 3 for all the tuples