2013-04-06 70 views

回答

3

你可以做這樣的事情:

key, value, name, password = (line.strip() for line in f) 

而且,在你的代碼,你似乎沒有接近文件,你所提取的信息之後。這可能會導致一些問題。您可以使用f.close(),也可以使用with聲明,通常認爲聲明更「pythonic」。

def get_values(input_file): 
    with open(input_file) as f: 
     key, value, name, password = (line.strip() for line in f) 
    return key, value, name, password 

爲了進一步簡化您的功能,我們實際上並不需要的值綁定到個人的名字,因爲我們沒有在功能上它們做任何事情。我們可以簡單地使用一個列表。

def get_values(input_file): 
    with open(input_file) as f: 
     info = [line.strip() for line in f] 
    return info 
+1

這,還要做'開放(INPUT_FILE)爲F'這將確保該文件被關閉。 – 2013-04-06 07:32:47

+0

謝謝,這是更好的 – dl8 2013-04-06 07:33:23

+0

@NathanVillaescusa謝謝,我已經提到 – Volatility 2013-04-06 07:35:53

0
with open(input_file) as in_f: 
    key, value, name, password = [line.strip() for idx, line in enumerate(in_f) if idx <= 3] 
3
import itertools 

with open('data.txt') as f: 
    key, value, name, password = (line.strip() for line in itertools.islice(f, 4)) 
相關問題