-2

Can someone explain to me what I am doing wrong ?

I have two files:

file1 looks like this

NOP7    305

CDC24   78

SSA1    41

NOP7    334 

LCB5    94

FUS3    183

file2 looks like this

SSA1    550 S   HSP70   1YUW

FUS3    181 Y   Pkinase 1QMZ

FUS3    179 T   Pkinase 1QMZ

CDC28   18  Y   Pkinase 1QMZ

And I'm using the following code-lit to get protein names that match in lists from other files

file = open('file1')

for line in file1:

    line=line.strip().split()

    with open('file2') as file2:

    for l in out:

        l=l.strip().split()

            if line[0]==l[0]:

                take=line[0]

                    with open('file3', 'w') as file3:

                        file3.write("{}".format(take))

What I get is a file with one protein name only

CDC28

And what I want is all the proteins that match, eg

SSA1

CDC28

FUS3

Please guide ...... ??

PS: when I print the result I get the required values (protein names) printed, but I am not able to write this to a file.

n4rzul
  • 4,059
  • 7
  • 45
  • 64
user3698773
  • 929
  • 2
  • 8
  • 15

1 Answers1

0

The problem that you have is that file(fname, 'w') truncates the file first, before attempting to write to it, meaning that every time you get a hit, you lose the previous result. What you want to do is to use file(fname, 'a') instead, which appends to the end of the file. However, you need to be aware that by default, this will not insert a trailing newline, so you have to do this manually, e. g. by using \n inside your format string like so: "{}\n".format(take).

Also, if you're on Python 3, you may want to look at changing your nested with statements into a single one with:

with file1 as open('file1', 'r'), file2 as open('file2', 'r'),\
     file3 as open('file3', 'a'):
     #put code here ...

Note, this is one of the few places where the backslash is necessitated to prevent lines from getting too long, and wrapping parentheses as recommended in PEP8 doesn't work, since then the with statement would assume the tuple to be our context manager.

Sari
  • 596
  • 7
  • 12
  • Thank you very much, its working now as I wanted it. Cheers ! – user3698773 Jan 29 '16 at 11:31
  • I'm using python 2.7, any suggestion for that how I can open multiple files at once with 'with' statement ? – user3698773 Jan 30 '16 at 21:24
  • I didn't really check up on it, but it looks like multiple with statements were actually included in 2.7 (according to the docs and the fact that it works on 2.7.11 on my machine right now). On 2.6, however, you would have to use `contextlib.nested` as shown in this question: http://stackoverflow.com/questions/7745164/multiple-context-with-statement-in-python-2-6 – Sari Jan 31 '16 at 16:09