#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2004
    Posts
    44
    Rep Power
    11

    Accessing text file


    If i have a text file with these value:

    Code:
    ## -- Text file --##
    
    nickname:realname
    something:anythin
    
    ##--- Text file --##
    how can I display the value of eg. nickname based on user input(eg: if the user type in nickname the the screen will display the real name)
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Posts
    624
    Rep Power
    34
    Read the lines of the file, and store them somewhere. Then just lookup in the store when someone types something.
    If you only want one-way lookups then a Dictionary is good to use.

    Code:
    pairs = {}
    
    for line in file('pairs.txt'):
        try:
            x, y = line.split(':')
            pairs[x] = y
        except: 
            #Ignore empty lines, etc.
            pass
    
    try:
        val = raw_input('Type something: ')
        print val, "links to", pairs[val]
    except KeyError:
        print val, "not found in pairs list"
  4. #3
  5. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    13
    Often these files are edited by hand and around the values you want you get unwanted character codes (e.g. tabs and spaces) . You can tidy it up easily:

    pairs[x.strip()] = y.strip()

    That might save a few hours bug-hunting.
    Grim
  6. #4
  7. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Just another example, based on sfb's with a few minor differences. Mainly to show the "if 'key' in dict" statment and stop unpacking errors.

    1. only splitting on the first colon, this helps stop unpacking errors resulting from lines containing more than one colon.
    2. uses if statments instead of try-except blocks. Just a personal preferance

    Code:
    #!/usr/bin/env python
    
    parts = {}
    
    for line in file('file.txt'):
        try:
            x, y = line.split(':', 1)
            parts[x] = y
        except:
            pass
         
    value = raw_input('Enter a value')
    
    if value in parts:
        print value, 'links to', parts[value]
    else:
        print value, 'not found in parts'
    Note: this does requite Python 2.3.

    Mark.
    Last edited by netytan; February 24th, 2004 at 03:14 PM.
    programming language development: www.netytan.com Hula


IMN logo majestic logo threadwatch logo seochat tools logo