2014-10-31 105 views
1

我試圖從.txt文件中獲取值到Python中的數組/列表中。 比方說,我在user.txt這樣的數據:從Python中的txt文件中的數組/列表

ghost:001 
    ghost:002 
    ghost:003 

所以,當我想把它作爲輸出:

'ghost:001','ghost:002','ghost:003' 

我用這個功能

def readFromFile(filename, use_csv): 
     userlist = '' 
     userlist_b = '' 
     print ("Fetching users from '%s'"% filename) 
     f = open (filename,"r") 
     for line in f: 
      userlist+=str(line) 

     userlist = "','".join(userlist.split("\n")) 
     userlist = "'" + userlist + "'" 
     userlist = "(%s)" %userlist 

     return userlist 

我的問題是我怎麼能這樣做: 我想打印特定用戶。類似於

idx = 2 
print("User[%s] : %s",%idx, %(array[idx])) 

*output:* 
User[2] : ghost:003 

如何形成陣列?

任何人都可以幫助我嗎?

+0

你想通過名稱的用戶? – 2014-10-31 02:57:16

回答

1

我將存儲在一個字典的用戶,其中鍵增加爲每個用戶:

d = {} 
with open("in.txt") as f: 
    user = 1 
    for line in f: 
     d[user]= line.rstrip() 
     user += 1 
print(d) 
{1: 'ghost:001', 2: 'ghost:002', 3: 'ghost:003'} 

如果你只是想要的用戶列表,並通過訪問索引:

with open("in.txt") as f: 
    users = f.readlines() 

print("User {}".format(users[0])) 
User ghost:001 
+0

謝謝,它的作品! :)) – noobsee 2014-11-06 06:52:39

0

調查加載詞典。這段代碼應該可以幫到你。

import json 
import pickle 

d = { 'field1': 'value1', 'field2': 2, } 

json.dump(d,open("testjson.txt","w")) 

print json.load(open("testjson.txt","r")) 

pickle.dump(d,open("testpickle.txt","w")) 

print pickle.load(open("testpickle.txt","r")) 
0

如果您希望文件(一個大字符串)分成較小的字符串,請不要生成一個新的字符串,然後再分開。只要每行追加到一個列表:

def readFromFile(filename, use_csv): 
    userlist = [] 
    print ("Fetching users from '%s'"% filename) 
    with open(filename,"r") as f: 
     for line in f.read(): 
      userlist.append(line) 
    return userlist 

array = readFromFile('somefile', use_csv) 
idx = 2 
print("User[%s] : %s" % (idx, array[idx])) 
0

不確定關於User['idx']部分的願望。

嘗試使用list comprehensions。 使用索引而不是字典,如果這是你所需要的。 (我可以添加一個字典版本,如果該行的一部分秒真的是你正在尋找了指數)

# read the file and use strip to remove trailing \n 
User = [line.strip() for line in open(filename).readlines()] 

# your output 
print "User[2] : %s"%User[2] 

# commented line is more clear 
#print ','.join(User) 
# but this use of repr adds the single quotes you showed 
print ','.join(repr(user) for user in User) 

輸出:

User[2] : ghost:003 
'ghost:001','ghost:002','ghost:003' 
相關問題