1

I was trying to get value from .txt file into array/list in python. Let's say I have this data in user.txt :

  ghost:001
  ghost:002
  ghost:003

So, when I want to output it as :

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

I use this function

   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

My question is how could I do this: I want to print specific user. Something like

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

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

How do I form the array?

Could anyone help me?

1
  • do you want the user by name? Commented Oct 31, 2014 at 2:57

4 Answers 4

1

I would store the users in a dict where the keys increment for each user:

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

If you just want a list of user and to access by index:

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

print("User {}".format(users[0]))
User ghost:001
Sign up to request clarification or add additional context in comments.

Comments

0

Look into loading dictionaries. This code should help you.

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

Comments

0

If you want the file (one big string) split out into smaller strings, don't build up a new string, then split it apart again. Just append each line to a list:

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

Comments

0

Not sure about the User['idx'] part of you desire.

Try to use list comprehensions. Use indexing rather than dictionaries if that's all you need. (I can add a dict version if the seconds part of the line is really the index you are looking up)

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

output:

User[2] : ghost:003
'ghost:001','ghost:002','ghost:003'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.