2017-04-07 7 views
1

私はPythonには新しく、助けて欲しいと思いました。 python:テキストファイルを読み込み、単一の列を抽出するループから変数を作成します。

私は、テキストファイルとプリントのみ拳列使用を読み込んで小さなスクリプトを持つforループ:

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

しかし、私は、forループで印刷されたすべての行を取得し、単一のものを作成したいですそれの変数。

つまり、テキストファイル/ etc/jbstorelistには3つの列があり、基本的には最初の列のみのリストを1つの変数の形で使用します。

ガイダンスをいただければ幸いです。ありがとうございました。

+1

ループに入る前にリストを宣言する: '= []' LST、次いで 'プリント置き換える(column.splitを()[0])'と 'lst.append(column.split()[0 ]) ' – alfasin

+0

ありがとうalfasin。私はこれをあまり理解していないので、あなたがそれを持っているようにあなたの要求を文法的に行いました。私はあなたの提案の最初の部分を実装する方法を誤解されなければならない無効な構文 :第1回= [] は、あなたはそれがスクリプトを超える書き込みを証明してくださいことはできますか?そして、 第一= [] ^ にSyntaxErrorを取得していますか – 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

関連する問題