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

python:从读取文本文件并提取单列的循环中创建变量,python,Python,我是python新手,希望能得到一些帮助 我有一个小脚本,它读取文本文件并使用for循环仅打印第一列: list = open("/etc/jbstorelist") for column in list: print(column.split()[0]) 但是我想获取for循环中打印的所有行,并为其创建一个变量 换句话说,文本文件/etc/jbstorelist有3列,基本上我想要一个只有第一列的列表,以单个变量的形式 任何指导都将不胜感激。多谢各位 由于您是Python新手,您可能

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

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

list = open("/etc/jbstorelist")
for column in list:
    print(column.split()[0])
但是我想获取for循环中打印的所有行,并为其创建一个变量

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


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

由于您是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])
#不要覆盖python内置代码。(即不要使用'list'作为变量名)
列表\=[]
#打开文件时使用with语句,如果
#当你离开街区的时候
打开(“/etc/jbstorelist”)作为文件流:
#当你在一个列表上循环时,你并没有在你要循环的列上循环
#在行或行上循环
对于filestream中的行:
#这里有一个你可能没有意识到的副作用。调用`.split()`
#如果您只需要
#要在可以传递的单个空白字符上拆分。拆分()`
#像这样的字符。拆分(“”)`
list.append(line.split()[0])

在进入循环之前声明一个列表:
lst=[]
然后将
print(column.split()[0])
替换为:
lst.append(column.split()[0])
。我不太明白这一点,所以我按照你的要求做了。我得到1st=[]^语法错误:无效语法我一定误解了如何实现你建议的第一部分:1st=[]你能演示一下吗?重写脚本?不是1st,是lst。我知道了。非常感谢。你知道有什么方法可以在打印列表时不使用撇号和逗号分隔行吗?谢谢你提供的信息。我已经有一段时间没有查看这个页面了,但是现在我已经清楚了逻辑。