Keif
Keif

Reputation: 11

python: create variable from loop that reads text file and extracts single column

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.

Upvotes: 1

Views: 51

Answers (1)

John
John

Reputation: 13699

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])

Upvotes: 2

Related Questions