1

I'm new to python and was hoping for some assistance please.

I have a small script that reads a text file and prints only the fist column using a for loop:

list = open("/etc/jbstorelist")
for column in list:
    print(column.split()[0])

But I would like to take all the lines printed in the for loop and create one single variable for it.

In other words, the text file /etc/jbstorelist has 3 columns and basically I want a list with only the first column, in the form of a single variable.

Any guidance would be appreciated. Thank you.

4
  • 1
    declare a list before entering the loop: lst = [] and then replace print(column.split()[0]) with: lst.append(column.split()[0]) Commented Apr 7, 2017 at 15:32
  • Thanks alfasin. I do not quite understand this, so I did your request literarly as you have it. And am getting 1st = [] ^ SyntaxError: invalid syntax I must be misunderstanding how to implement the first part of your suggestion: 1st = [] Can you please demonstrate it writing the script over? Commented Apr 7, 2017 at 15:42
  • It's not 1st it's lst. Commented Apr 7, 2017 at 15:44
  • I got it. Thank you. Do you know any way of printing the list without the lines being separated by apostrophes and commas? Commented Apr 7, 2017 at 15:49

1 Answer 1

2

Since you're new to Python you may want to come back and refernce this answer later.

#Don't override python builtins. (i.e. Don't use `list` as a variable name)
list_ = []

#Use the with statement when opening a file, this will automatically close if
#for you when you exit the block
with open("/etc/jbstorelist") as filestream:
    #when you loop over a list you're not looping over the columns you're
    #looping over the rows or lines
    for line in filestream:
        #there is a side effect here you may not be aware of. calling `.split()`
        #with no arguments will split on any amount of whitespace if you only
        #want to split on a single white space character you can pass `.split()`
        #a <space> character like so `.split(' ')`
        list_.append(line.split()[0])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the info. I haven't checked this page in a while but the logic is clear to me now.

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.