im a newbie to python, still learning as of today. as a part of my 'self-training' i listed some topics to practice every week but i was not able to run it successfully and im stuck. what i wanted with my activity is for it to read a .txt file which contains tabular data, place each line of the file in an array and return a line i wanted to call.

hope you could help me with this. thank you :)

Edited 6 Years Ago by bettersaid: n/a

For most needs Python list correspond with array. You can split fields by line.split('\t'). You can test if value is in field by in and usualy also strip and lower methods come handy.

matrix = {}
name = open("filename.txt", "r")
read = name.read()


def getFullName(name):

    try:
        data = matrix[string.lower(name)]
        assert data != "", "Error"
        return data

    except KeyError:
        print sys.exc_type, ":" "% is not in the list." %
        sys.exc_value
        print

    while 1:
        name = raw_input("Enter first name or x to exit:")
        if name == "x":
            break

        file = getFullName(name)
        if name !=None:
            print "%s's family name is %s" % (name, fullName)
            print

i tried putting it in matrix but i dunno how to include the file inside the matrix and how to call each line. i know i need more practice, but please bear with me. thanks

is this how it should be?

for line in file:
            array=tuple(map(line.strip().split("filename, file")))
            array.append(array)

Edited 3 Years Ago by Nick Evan: Fixed formatting

matrix = {}
name = open("filename.txt", "r")
read = name.read()


def getFullName(name):
    
    try:
        data = matrix[string.lower(name)]
        assert data != "", "Error"
        return data
    
    except KeyError:
        print sys.exc_type, ":" "% is not in the list." %
        sys.exc_value
        print
        
    while 1:
        name = raw_input("Enter first name or x to exit:")
        if name == "x":
            break
        
        file = getFullName(name)
        if name !=None:
            print "%s's family name is %s" % (name, fullName)
            print

i tried putting it in matrix but i dunno how to include the file inside the matrix and how to call each line. i know i need more practice, but please bear with me. thanks

is this how it should be?

for line in file:
            array=tuple(map(line.strip().split("filename, file")))
            array.append(array)

Here is my code for using lists with Pythonic way by list comprehensions for building lists.

def query(name):
    return [familyname
            for firstname, familyname in names
            if firstname.lower() == name.lower()]

#build list of names from lines in filename.txt, if name drops any empty lines
names=[name.strip().split('\t') for name in  open("filename.txt", "r") if '\t' in name] 
print repr(names)
# separate first and family names giving us list of tuples
names=[(firstname.rstrip(),familyname) for firstname, familyname in names]
    
while True:
    print('-'*60)
    name = raw_input("Enter first name or x to exit:\n")
    if name == "x":
        raise SystemExit, "Thanks of using name database!"
    familyname=query(name)
    print("Found %i answer%s:\n%s" %
          (len(familyname),
           's' if len(familyname)>1 else '', # s for plural when multiple answers
           '\n'.join(familyname)) if len(familyname) else   # multiple answers newline between them
                "First name %r is not in data file" % name) # %r format to get quotes around name when no answers

Edited 6 Years Ago by pyTony: n/a

To get a matrix, you would have to split each record in the file. The file will be read in as a single dimension list if each record has a newline. You then have to split each record on the individual fields to get a matrix that you can access. This program creates a file first, with comma delimited fields and then reads it back in, splits into fields on the commas, and then looks up individuals. If you only want to look up first name you would use a dictionary instead of a list-of-lists/matrix.

def print_name(rec):
    print
    print "first name =", rec[0]
    print "last name = ", rec[1]
    print "street =    ", rec[2]
    print "city =      ", rec[3]
    print "state =     ", rec[4]


## output the file
fname = "./test_name"
fp_out = open(fname, "w")
fp_out.write("Bill,Smith,132 Main St.,Anytown,MI\n")
fp_out.write("Mary,Jones,456 Elm Ave.,Metropolis,NY\n")
fp_out.write("Jered,Weaver,2000 Gene Autry Way,Anaheim,CA")
fp_out.close()

## read it using readlines to get a list of records
fp = open(fname, "r")
single_list = fp.readlines()
print single_list

## split each record and store in a separate list
list_of_items = []
for rec in single_list:
    rec = rec.strip()
    one_rec_list = rec.split(",")
    print one_rec_list
    list_of_items.append(one_rec_list)

## look up first name = "Mary"
for rec in list_of_items:
    if rec[0] == "Mary":
        print_name(rec)

## look up city = "Anaheim"
for rec in list_of_items:
    if rec[3] == "Anaheim":
        print_name(rec)
This question has already been answered. Start a new discussion instead.