Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to a file

Tags:

python

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.

like image 445
user587646 Avatar asked Jul 09 '26 17:07

user587646


1 Answers

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)
like image 193
Greg Hewgill Avatar answered Jul 12 '26 05:07

Greg Hewgill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!