python:从循环创建变量,读取文本文件并提取单列

时间:2017-04-07 15:30:16

标签: python

我是python的新手,希望能得到一些帮助。

我有一个小脚本,它读取文本文件,并使用for循环打印第一列:

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

但是我想在for循环中打印所有行并为它创建一个单独的变量。

换句话说,文本文件/ etc / jbstorelist有3列,基本上我想要一个只有第一列的列表,以单个变量的形式。

任何指导都将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:2)

由于您是Python的新手,您可能希望稍后再回过头来参考此答案。

#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])
相关问题