繁体   English   中英

Python中txt文件中的数组/列表

[英]Array/List from txt file in Python

我试图从.txt文件中获取值到python中的数组/列表中。 假设我在user.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

如何形成阵列?

有人可以帮我吗?

我会将用户存储在字典中,其中每个用户的键会递增:

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

查看加载字典。 此代码应为您提供帮助。

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"))

如果要将文件(一个大字符串)拆分为较小的字符串,请不要建立新的字符串,然后再将其拆分。 只需将每一行添加到列表中:

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

不确定您想要的User['idx']部分。

尝试使用列表推导 如果仅此而已,请使用索引而不是词典。 (如果该行的秒部分确实是您要查找的索引,则可以添加字典版本)

# 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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM