Reputation: 117
I have been trying to write to a file,but it kept writing them on a single line with commas, and square brackets at both ends. How do I write to a file without the square brackets, commas and newline for each rows or lines of the file. Column 6 must remained sorted in descending order.
This is the output from the code below:
[NP_001026855.1, N, 1, YES, 96.4765%, 0.9823825] [NP_597716.1, D, 1, YES, 96.2573%, 0.9812865]
Here's my codes.
lines = open("file.txt", "r").readlines()
outfile = open("file2.txt",'w+')
lines = [x.split() for x in lines]
lines.sort(key=lambda x:x[5], reverse=True)
for i in lines:
outfile.writelines(i)
The required output should be:
NP_001026855.1 N 1 YES 96.4765% 0.9823825
NP_597716.1 D 1 YES 96.2573% 0.9812865
Thanks guys for your contribution.
Upvotes: 2
Views: 4590
Reputation: 993095
Each element of lines
is itself an array. Try:
for i in lines:
outfile.write(" ".join(i) + "\n")
The .join()
method takes an array i
and concatenates all the elements together with a space " "
between each element. Then a newline "\n"
is added to make sure your output is broken up into separate lines.
Alternately, you don't even have to save the splitted copy of all the lines:
lines = open("file.txt", "r").readlines()
outfile = open("file.2txt", "w")
lines.sort(key=lambda x: x.split()[5], reverse=True)
for i in lines:
outfile.write(i)
Upvotes: 9