Hey fellas,

I have searched for this answer for about an hour on and off and cannot find anything so sorry to have to resort to posting.

I have a list [a, b, c, d]

And I want to write it to a simple output file, but I want it to be written with a new line after each character so that it appears in the file as:

There is more going on in the program but this is the only thing I really am concerned with at the moment. It's complaining when I insert a newline character into the writeout (I assume this only applies to strings).

Here is a snipet of my code if that helps:
--------------------------------------------- (Declarations separated below)
temp = [ ]

col = int(raw_input('Please select a column (starting at 0) from your infile, %s:' % (infile)))

for line in f:
line = line.split() #Line has been split into a list of components [a,b,c...]
temp.append(line[col]) #Write the user-specified column into the empty list, "temp"

for i in range(len(temp)): #This line basically just prints one by one

7 Years
Discussion Span
Last Post by jlm699
Featured Replies
  • 1

    This was the second entry from a Google for "python list write" [url]http://www.daniweb.com/forums/thread173615.html[/url] and effbot is usually in search results. This explains writelines(), but writelines() does not insert a newline but is useful for transferring lists to a file. [url]http://effbot.org/zone/python-list.htm[/url] Read More


Thanks for the help woooee

Hey, it helps to read the code posted in this forum if it's in code tags. And also, if you wanted to do a single write that included your newline you can do something like this:

temp = ["4", "5", "6", "7", "8"]
for i in range(len(temp)):
    f.write("%s\n" % temp[i])

However that's not very pythonic (the for loop), but this is:

for item in temp:
    f.write("%s\n" % item)

Or perhaps instead of this:

for line in f:
    line = line.split() 

for i in range(len(temp)):

You could simplify it and do this:

o.open(..., 'w')
o.write( '\n'.join( [ line.split()[col] for line in f ] ) )
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.