views:

34

answers:

3

Im using a function to return a text file that is tab delimited and read in, the format of the text file is:

1_0 NP_250397 100.00 140 0 0 1 140 1 140 6e-54 198

1_0 NP_250378 60.00 140 0 0 1 140 1 140 6e-54 198

1_0 NP_257777 70.00 140 0 0 1 140 1 140 6e-54 198

My code used to return is:

def print_file(x):
    h = open('/home/me/data/db/test.blast', 'r')
    return h.readlines()

But when its printed it looks like:

['1_0\tNP_250397\t100.00\t140\t0\t0\t1\t140\t1\t140\t6e-54\t 198\n', '1_0\tNP_250397\t100.00\t140\t0\t0\t1\t140\t1\t140\t6e-54\t 198\n', '1_0\tNP_250397\t100.00\t140\t0\t0\t1\t140\t1\t140\t6e-54\t 198\n']

Is there a way of returning the file, while aslo retaining formatting?

A: 

return h.read() would return the file's contents as a single string, and therefore "retain formatting" if that's printed, as you put it. What other constraints do you have on the return value of the peculiarly-named print_file (peculiarly indeed because it doesn't print anything!)...?

Alex Martelli
h.readlines() is returned to another python script where it is printed
Gary
@Gary, if printing it is all that's needed then `h.read()` is the perfect solution.
Alex Martelli
+2  A: 

If you want print_file to actually print the file as the function name suggests

def print_file(x):
    with open('/home/me/data/db/test.blast', 'r') as h:
        for line in h:
            print line

If you want to return the contents of the file as a single string

def print_file(x):
    with open('/home/me/data/db/test.blast', 'r') as h:
        return h.read()

If your Python is too old to use the with statement

def print_file(x):
    return open('/home/me/data/db/test.blast', 'r').read()

Aside: You may be interested to know that the csv module can work with tab delimited files too

gnibbler
I get a invalid syntax error when i tyr you second method?
Gary
@Gary, if you are using python2.5 include this line at the top of the file `from __future__ import with_statement`
gnibbler
tried that, still get a invalid syntax error
Gary
Thank you, your last messgae didnt appear until i submitted my last comment
Gary
A: 

When you print out a list, Python prints the list in a kind of raw format that represents how it's stored internally. If you want to eliminate the brackets and commas and quotes and want the tabs expanded, you must print out each string individually.

for line in print_file(x):
    print line

And could you please pick a more appropriate name for print_file, since it isn't really printing anything? It's adding a bit of cognitive dissonance that isn't helping your problem.

Mark Ransom