简体   繁体   中英

Creating a List of Names from an Input File

I'm going crazy trying to figure out how to get rid of the error 'str has no attribute append'. I need to add the people's names to name_list from the input file.

A typical line from the input file would read:

Tameka harris 3/4/17

Here is the code I have so far:

def process_input(file1, any_dict, any_set):

    #open input file
    customer_input_file = open(file1, 'r')


    #initialize a list to store info by line
    line_list = []

    #Create a name counter
    index = 0

    #read file line by line
    for line in customer_input_file:
        #split the line
        line_list = line.split()
        #slice the list to make a list with only names and no dates
        name_list = line_list[-1]
        #create a variable for first name from list
        fname = name_list[0].title()
        #create a last name variable from list
        lname = name_list[1].title()
        #add the two name variables together as a new list
        input_name = [fname + ' ' + lname]


        #add names to name list
        name_list.append(input_name)

        #add names to name list
        any_set.add(name_list[index])

        #count the times a name repeats in the name list
        any_dict[input_name] = name_list.count(input_name)


        #add 1 to index
        index += 1


    #Close input file
    customer_input_file.close
# slice the list to make a list with only names and no dates
name_list = line_list[-1]

The above returns the last item in the list which is a string and that's why name_list.append(input_name) throws the error.

What you need is to exclude the last item:

name_list = line_list[:-1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM