1

Hello I need your help on the following problem. I am parsing the file that looks like this

@<TRIPOS>MOLECULE
NAME123
line3
line4
line5
line6
@<TRIPOS>MOLECULE
NAME434543
line3
line4
line5
@<TRIPOS>MOLECULE
NAME343566
line3
line4

I currenly have this code that is working ok...

mols = [] 
with open("test2.mol2", mode="r") as molfile: 
    for line in molfile: 
        if line.startswith("@<TRIPOS>MOLECULE"): 
            mols.append(line) 
        else: 
            mols[-1] += line
#
for i in range(len(mols)): 
    out_filename = "file%d.mol2" % i 
    with open(out_filename, mode="w") as out_file: out_file.write(mols[i]);

but whem I tried to save the files with name according to the second field of array, the one after @MOLECULE (NAME....) with code like this - it doesn't work. Please, help me to fix the code. Thank's!

for i in mols:
    out_filename = str(i.split()[1]) + ".mol2" % i
    with open(out_filename, mode="w") as out_file: out_file.write(mols[i]);

The error is

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: not all arguments converted during string formatting

3 Answers 3

1

I recommend using a more structured list:

for line in molfile:
    if line.startswith("@"):
        mols.append([])
        mols[-1].append(line) # Keep first line
    else:
        mols[-1].append(line)

then:

for i in mols:
    out_filename = i[0].strip() + ".mol2"
    with open(out_filename, mode="w") as out_file:
        out_file.write(''.join(i));
Sign up to request clarification or add additional context in comments.

5 Comments

But this one output just the first array, and not the others.
And I also need @<TRIPOS>MOLECULE as first line of every file.
Sorry, still produce 1 file instead of all avaliable arrays in mols
for i in mols: out_filename = i[1].strip() + ".mol2" with open(out_filename, mode="w") as out_file: out_file.write(''.join(i));
Well, it worked for me: Idk what went wrong in the mind to mind transmission, but my, aren't these antennas crufty? I'm guessing you got it working, though.
1

Your code includes ".mol2" % i which looks it's supposed to be string interpolation, but provides no placeholders to be interpolated. Assuming you know how to use string interpolation with the % sign, perhaps you meant something like ".mol%s" % i?

1 Comment

No, I am new to python. Every file should be ended with .mol2
0

When you use "%" followed by a variable name in Python, it's going to look for a string formatting sequence in your string and attempt to format it. In your second code snippet, Python isn't finding a format specifier in your string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.