2017-04-07 114 views
1

我是新來的蟒蛇,並希望一些幫助,請。蟒蛇:創建循環變量讀取文本文件並提取單個列

我有一個小腳本讀取的文本文件和打印只用拳頭列一個循環:

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

但我想借此在打印的所有行的for循環,並創建一個單一的變量爲它。

換句話說,文本文件/ etc/jbstorelist有3列,基本上我想要一個只有第一列的列表,以單個變量的形式。

任何指導,將不勝感激。謝謝。

+1

進入循環之前聲明列表:'LST = []'然後更換'打印(column.split()[0])'與:'lst.append(column.split()[0 ])' – alfasin

+0

謝謝alfasin。我不太明白這一點,所以我按照你的要求以文字方式完成了你的請求。而我得到 1 = [] ^ 語法錯誤:無效的語法 我必須誤解如何實現你的建議的第一部分:1 = [] 能否請你展示它寫劇本了嗎? – Keif

+0

這不是第一次,它是第一次。 – sdasdadas

回答

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

感謝您的信息。我有一段時間沒有檢查過這個頁面,但現在我明白了這個邏輯。 – Keif