1

I have a text file containing multiple columns. I can successfully print all the items in the 2 columns I am interested in by using this code:

with open(file) as catalog:
    for line in catalog:
        column = line.split()
        if not line.startswith('#'): #skipping column labels
            x = float(column[3])
            y = float(column[4])

Now if I add a print(x) command inside the 'if not' loop, it prints all of the x values. But if I put print(x) outside of the loop it only prints the last item. What I want is to be able to access the full array of x and y values anywhere in my code. I also need to be able to access the x/y array items individually, so I can say x[2], and it will give me the third value in the x array. I can not get this part to work even inside of the 'if not' loop. Thanks for any help, I have only been using Python for a couple of weeks..

5
  • do you want the x and y values together? Commented Jul 28, 2014 at 19:20
  • no, separate. the answers below did what I wanted
    – deedsy
    Commented Jul 28, 2014 at 19:22
  • just out of curiosity, does anyone know why I got downvoted for my question? I'd hate to get my account suspended, and I thought I formatted correctly..
    – deedsy
    Commented Jul 28, 2014 at 19:23
  • thanks, anything specifically you recommend for future posts? Thinking I could add some of the things I tried (even though most of them were probably way off)
    – deedsy
    Commented Jul 28, 2014 at 19:39
  • Just a tip: Move the column = line.split() inside the if not block. The way it is now, you're wasting time splitting lines that you then discard. Commented Jul 28, 2014 at 19:47

2 Answers 2

2

Save your Xs and Ys in a list:

X_list = []
Y_list = []
with open(file) as catalog:
    for line in catalog:
        column = line.split()
        if not line.startswith('#'): #skipping column labels
            x = float(column[3])
            y = float(column[4])
            X_list.append(x)
            Y_list.append(y)
#then print the lists if you wish
print(X_list)
print(Y_list)
0
-1

It sounds like you'll need to build a list of values.

with open(file) as catalog:
    x_values = []
    y_values = []
    for line in catalog:
        column = line.split()
        if not line.startswith('#'): #skipping column labels
            x_values.append(float(column[3]))
            y_values.append(float(column[4]))
0

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.