tags:

views:

194

answers:

6

Hi, Part of my script is taking values and putting them to a text file delimited by tabs. So I have this:

for linesplit in fileList:
    for i in range (0, len(linesplit)):
        t.write (linesplit[i]+'\t')

I get as an output in the file what I expect in the first line but in the following lines they all start with a \t in them, like is:

value1    value2    value3
    value1    value2    value3
    value1    value2    value3

Also, why don't I need to add a t.write('\n') after the second FOR loop to create the newlines? I would expect the code above to produce one long line of tab separated values but it doesn't. If I include the t.write('\n') then the tabs issue is resolved but I get double '\n'...

+1  A: 

I'm sorry... After I hit submit it dawned on me. My last value already has a \n in it which causes the newline.

greye
ah, 24 seconds.
SilentGhost
+6  A: 

it doesn't produce what you want because original lines (linesplit) contain end of line character (\n) that you're not stripping. insert the following before your second for loop:

linesplit = linesplit.strip('\n')

That should do the job.

SilentGhost
+1  A: 

Your last value must have a "\n" which causes both problems: The first problem because it outputs '\t' after the newline, the second problem should be obvious - the mystery newlines are coming from your last value.

Draemon
+1  A: 

you linesplit variable could have newlines. just use strip() to remove it.

ghostdog74
+1  A: 

Your "value3" strings are really "value3\n", which explains the magical newlines and the extraneous tabs on all but the first line.

John Kugelman
A: 

The inner loop isn't required. Perhaps you meant to use:

t.write('\t'.join(linesplit))
Moshe