2

When I try to use indexing to get the last element of my line, it does not work( prints out a blank line). However, when I print the original line it works.

with open( newFile,"w") as f: 

    f.write("Model Number One" + "\n")
    for l in lines:
        if "ATOM" in l : 
            f.write(l[-1]) #Does NOT work, prints empty line
            f.write(l) # Prints the whole linem when I only want the last element of the line

When index is used When index is not used

3
  • 1
    What's lines? Is it a list of strings or a list of lists of strings? Commented Mar 14, 2021 at 0:54
  • It is a list of strings! Commented Mar 14, 2021 at 14:19
  • If lines is a list of strings, then each l in lines is a string, and each index is a single character. To split it into a list of whitespace-separated words you want split(). Commented Mar 14, 2021 at 18:27

3 Answers 3

2

The cause might be that the line has a new line character at the end. If the last element of the line is a "\n" since the file has multiple lines, then it will definitely print a blank line.

Sign up to request clarification or add additional context in comments.

1 Comment

I figured that might be, so I tried f.write[-2], f.write[-3], and etc, but it printed numbers from 0 to 9. I knew this was wrong because the last column starts at 1 and ends at 41.
2

Each line is a string, and so each index is a single character, with the last one being a linebreak ('\n'). If you want to get whitespace-separated substrings out of that line, use strip to remove the linebreak, and split to split the resulting string on whitespace:

with open( newFile, "w") as f: 
    f.write("Model Number One" + "\n")
    for l in lines:
        elems = l.strip().split()
        if "ATOM" in elems: 
            f.write(elems[-1] + "\n")

Comments

0

As Kengru mentioned, there could be a newline at the end. To test try f.write(l[-2]) instead of f.write(l[-1]).

2 Comments

I figured that might be, so I tried f.write[-2], f.write[-3], and etc, but it printed numbers from 0 to 9. I knew this was wrong because the last column starts at 1 and ends at 41
If possible, copy paste the last line of that file you're trying to read.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.