[Tutor] files in a directory

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Jan 31 09:14:16 CET 2005



> Now that I am reading many files at once, I wanted, to
> have a tab delim file op that looks like this:
>
> My_coors         Int_file 1     Int_file2
> IntFile3
> 01:26               34          235
> 245.45
> 04:42              342.4        452.4            45.5
> 02:56              45.4         34.5             557.8

[code cut]


Hi Kumar,

Ok, I think I see the source of the bug.  Let's check how the code writes
each of my_vals:

>     for line in my_vals:
>         f2.write(line+'\t') => asking for tab delim..
>         f2.write('\n')

The problematic statement is the last one: between each of the values, the
code writes a newline as well as the tab character.

Push the newline-writing code outside of the loop, and you should be ok.


As a note: you can simplify the tab-writing code a bit more by using a
string's "join()" method.  For example:

###
>>> "/".join(["this", "is", "a", "test"])
'this/is/a/test'
###

So we can join a bunch of elements together without using an explicit
'for' loop.  In your program, you can use join() to create a large string
of the my_vals elements with tabs joining them.  If you'd like to see
more, the library documentation:

    http://www.python.org/doc/lib/string-methods.html#l2h-192

mentions more information on the join() method and the other methods that
strings support.


Please feel free to ask more questions on any of this.  (But when you
reply, try to cut down on the number of lines that you quote from the
previous message.  I almost missed your question because I couldn't see it
at first!  *grin*)



More information about the Tutor mailing list