Reputation: 461
I want to know how to save an array to a file. You already helped me a lot, but I have more naive questions (I'm new to Python):
@<TRIPOS>MOLECULE
NAME123
line3
line4
line5
line6
@<TRIPOS>MOLECULE
NAME434543
line3
line4
line5
@<TRIPOS>MOLECULE
NAME343566
line3
line4
I am currently have this code, but it's save only the last item from the array no the all listed in the items_grep
. How to fix this?
items = []
with open("test.txt", mode="r") as itemfile:
for line in itemfile:
if line.startswith("@<TRIPOS>MOLECULE"):
items.append([])
items[-1].append(line)
else:
items[-1].append(line)
#
# list to grep
items_grep = open("list.txt", mode="r").readlines()
# writing files
for i in items:
if i[1] in items_grep:
open("grep.txt", mode="w").write("".join(i))
Thank you in advance!
Upvotes: 1
Views: 3021
Reputation: 17086
The reason your file is only showing the last value is because every time you open the file with the w
flag, it erases the existing file. If you open it once and then use the file object, you'll be fine, so you'd do (note, this is not a very clean/pythonic way of doing it, just being clear about how the open command works)
myfile = open("grep.txt", "w")
for i in ...
if i[1] ...:
myfile.write(i + '\n')
Easy way to handle this would be to do a list comprehension first and then join, e.g.:
newstr = '\n'.join([''.join(i) for i in items if i[1] in items_grep])
Then just write the entire string to the file at once. Note that without adding the \n
between items, you won't end up with each item on a new line, instead they will all be added one after the other without spaces.
You should also consider using the with
keyword to auto close the file.
with open("grep.txt","w") as f:
f.write(newstr)
Upvotes: 1