Reputation: 461
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
Upvotes: 1
Views: 159
Reputation: 7035
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));
Upvotes: 1
Reputation: 329
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.
Upvotes: 0
Reputation: 251378
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
?
Upvotes: 1