dfernan
asked on
How to use file.write in python without new line
Hi,
If I do a for loop in python of this list,
file = open("foo.txt",'w')
list = ["hi", "how", "are", "you"]
for element in list:
file.write(element)
it will write a file like this
hi
how
are
you
I.e., put a new line after each element...
What if I don't want a new line after each element except for the last element in the list? is that possible?
I.e., I want:
hi how are you \n....
Please advise.
Thanks!
If I do a for loop in python of this list,
file = open("foo.txt",'w')
list = ["hi", "how", "are", "you"]
for element in list:
file.write(element)
it will write a file like this
hi
how
are
you
I.e., put a new line after each element...
What if I don't want a new line after each element except for the last element in the list? is that possible?
I.e., I want:
hi how are you \n....
Please advise.
Thanks!
Which version of Python are you using? I don't seem to get that behavior on Linux or Windows. In the Windows version, it printed to the screen with newlines, but in the file, the data was all on one line.
ASKER
python 2.6.2 linux...
I do not believe the code inserted the \n. I guess that you used the "print element" when printing to console. The print adds the \n automatically, unless you add a comma after the last argumens. Or you can use the sys.stdout.write() to write exactly what you want. Try the following:
b.py
It prints on my Windows console (but it definitely must be the same on a Linux console):
The same is in the file.
b.py
import os
import sys
fname = 'foo.txt'
# Just to be sure you are not looking at old results ;)
if os.path.isfile(fname):
os.remove(fname)
# You should not use the 'file' identifier for your variables.
# You should not use the 'list' identifier for your variables. It masks the
# built-in list() function.
f = open(fname, 'w')
lst = ['hi', 'how', 'are', 'you']
for element in lst:
f.write(element) # this will never write \n to your output
f.close() # you should always close the open file
# The same to stdout.
for element in lst:
sys.stdout.write(element) # this will never write \n to your output
It prints on my Windows console (but it definitely must be the same on a Linux console):
c:\tmp\___python\dfernan\Q_27366174>python b.py
hihowareyou
The same is in the file.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.