Solved

How to use file.write in python without new line

Posted on 2011-09-29
4
403 Views
Last Modified: 2012-06-21
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!
0
Comment
Question by:dfernan
  • 2
4 Comments
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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.
0
 

Author Comment

by:dfernan
Comment Utility
python 2.6.2 linux...
0
 
LVL 28

Expert Comment

by:pepr
Comment Utility
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
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

Open in new window


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

Open in new window


The same is in the file.
0
 
LVL 28

Accepted Solution

by:
pepr earned 250 total points
Comment Utility
Or there may be another reason for making you believe that the f.write() adds the \n.  You may have obtained your lst via fin.readline() where fin is the text file opened for reading.  When reading text files in Python, you get the lines that contain also the final \n.  If this is the case, then you have just got the copy of the existing \n's.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

The really strange introduction Once upon a time there were individuals who intentionally put the grass seeds to the soil with anticipation of solving their nutrition problems. Or they maybe only played with seeds and noticed what happened... Som…
Here I am using Python IDLE(GUI) to write a simple program and save it, so that we can just execute it in future. Because when we write any program and exit from Python then program that we have written will be lost. So for not losing our program we…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now