Retain formatting
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 wa开发者_运维问答y of returning the file, while aslo retaining formatting?
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
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!)...?
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.
精彩评论