gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:07:10 24 4
gpt4 key购买 nike

我试图将 .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

关于python - Python 中 txt 文件的数组/列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26666799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com