Thread: Read From File

    #1
  1. Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Dec 2004
    Location
    Meriden, Connecticut
    Posts
    1,797
    Rep Power
    154

    Read From File


    Im having a little problem with the way I want my program to read data from text documents. My program, which is a battle.net bot, has certain commands that add users to a text document, database.txt. It may add them with access, or as $hitlist, etc. ($hitlist is a autoban). My problem is trying to read from database.txt whether they have access and what their access is, or whether they are ****listed. After writing users to the database, there might be something like this in database.txt.

    Yegg 100 # Yegg being the user and 100 being the access level
    rockstar453 50
    warriorguy4332 $hit# $hit meaning $hitlisted

    How can I get my program to figure out whether they have access or are $hitlisted. And if they have access, how do I find out what their access is?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2002
    Posts
    89
    Rep Power
    13
    Code:
    file = open("database.txt", "r")
    
    for line in file:
        user = line.split()
        if user[1] == "$hit":
            print "user is $hitlisted"
        else:
            print "access level is " , user[1]
  4. #3
  5. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    You could also read the file into a dictionary for easier use in the program i.e. using a list comprehension or generator expression (below)

    Code:
    >>> users = dict(line.split() for line in file('users.txt'))
    >>> users
    {'user4': '$hit', 'user2': '100', 'user3': '19', 'user1': '1'}
    >>>
    I like this (especially the use of the generator expressions) but if you need to do something for complex then you will need to do something like this:

    Code:
    >>> users = {}
    >>>
    >>> for line in file('users.txt'):
    ...     user = line.split()
    ...     try:
    ...         users[user[0]] = int(user[1])
    ...     except ValueError:
    ...         users[user[0]] = user[1]
    ...
    >>> users
    {'user4': '$hit', 'user2': 100, 'user3': 19, 'user1': 1}
    >>>
    Note: This could also be written to test if user[1] == '$hit' before type-casting but this may cause errors if for some reason another string/char value is written to the file instead of a permission level [number].

    Enjoy,

    Mark.
    programming language development: www.netytan.com Hula


IMN logo majestic logo threadwatch logo seochat tools logo