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.
Each element of
linesis itself an array. Try:The
.join()method takes an arrayiand 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: