0

I am having trouble writing the entire list into an outfile. Here is the code:

with open(infline, "r") as f:
    lines = f.readlines()
    for l in lines:
        if "ATOM" in l :
            split = l.split()
            if split[-1] == "1":
                print(split)
                #print(type(split))

            with open( newFile,"w") as f:
                f.write("Model Number One" + "\n")
                f.write(str(split))

When I use print(split) it allows me to see the entire list (image below):

with open(infile, "r") as f:

    lines = f.readlines()
    for l in lines: 
        if "ATOM" in l : 
            split = l.split()
            if split[-1] == "1":
                #print(split)
                print(type(split))
            
            with open( newFile,"w") as f: 
                f.write("Model Number One" + "\n")
                for i in range(len(split)):
                    f.write(str(split))

Image of entire list

However, when I try to use f.write(split) I get an error because the function can only take a str not a list. So, I used f.write(str(split)) and it worked. The only issue now is that it only writes the last item in the list, not the whole list.

image of the output for f.write (str(split))

Casey
  • 10,297
  • 11
  • 59
  • 88
Anna
  • 31
  • 2

1 Answers1

0

The function print is slightly more permissible than the method f.write, in the sense that it can accept lists and various types of objects as input. f.write is usually called by passing pre-formatted strings, as you noticed.

I think the issue with the code is that the write routine is nested inside the code. This causes Python to erase any contents stored inside newFile, and write only the last line read (l).

The problem can be easily fixed by changing the open call to open( newFile,"a"). The flag "a" tells Python to append the new contents to the existing file newFile (without erasing information). If newFile does not exist yet, Python will automatically create it.

C-3PO
  • 1,181
  • 9
  • 17
  • It worked! The only issue now is that doesn't end. It keeps repeating the last line without ever stopping. The code should stop at line 501, but it continues to line 20,583 – Anna Mar 14 '21 at 18:41
  • I guess the issue is that the last 2 lines of code repeat the entire `split` sentence for every element in `split`. You could try replacing the last 2 lines of code by just `f.write(str(split)+'\n')` – C-3PO Mar 14 '21 at 18:47