1

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!

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

8 Comments

Thank's a lot! The problem was with the join, can you please describe more details. Why the last only?
updated to add the answer to the question. you reopen the file in every iteration of your for loop (so it erases every time)
@JohnAmraph So, the reason that the '\n'.join() fixed the problem for you is because it combined all your file writes into one statement (so none of them overwrote each other :P)
So, it's kind of join-ing the writing?
If you wanted to open a file multiple times without erasing ("truncating") the content, you'd have to first close the file, then reopen it in append mode open(fname, 'a'), rather than write mode open(fname, 'w'). Write mode always assumes you want to discard the previous content, and this is also how most programs (text editors, e.g.) save files.
|

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.