I am pulling a name, address, phone number from a text file. The items are delimited with a comma. I pull them into a variable. How can I pull them in or parse them out?

I'm not sure if this is a tuple or a list or what, but when I use vari=filename.read() it puts the variable as 'name,address,phone' and I cannot get them split up into separate fields.

Any advise would be appreciated, and I'm sorry about the format of this message I saw something about code wrap but it disappeared from my screen when I typed.


The output shows 'vari' contains every item from FILE and I cannot separate them.

Edited 3 Years Ago by happygeek: fixed formatting

You can do fh.read().split(',') to split the line into a list of

Python also has a built-in csv module.

As to the code tags, you want to change the first one to [ code=python ]: leave the second one as is.

Here is one way to do this sort of thing ...

# name, address, phone data processing

data = """\
Carl Arm, 123 Malt Rd Carlson MO, 712-123-4567
Frank Fern, 21 S. West St Blippo CA, 901-321-7654
Mimi Mink, 13 Arbor St Draft NY, 204-777-9631"""

filename = 'MyAddBook.txt'
# create a test file
fout = open(filename, "w")

# now read the address file back in as a list of lines
fin = open(filename, "r")
raw_list = fin.readlines()

# test it, you should get a list with each data line being a string item ...

# now process this raw list to get a list of [name, address, phone] lists
my_list = []
for line in raw_list:
    # remove any trailing newline
    line = line.rstrip()
    # split the line at the commas
    name, address, phone = line.split(',')
    # remove any leading spaces from address and phone
    address = address.lstrip()
    phone = phone.lstrip()
    #print(name, address, phone)
    my_list.append([name, address, phone])

# test it ...

# search the list for a complete name ...
search = 'Mimi Mink'
for item in my_list:
    if search in item:
        # unpack the item (sub list)
        name, address, phone = item


# another search, this time part of an address ...
search = 'Blippo CA'
for item in my_list:
    # unpack the item (sub list)
    name, address, phone = item
    # you are looking for a part of the address
    if search in address:

my beautified output -->
['Carl Arm, 123 Malt Rd Carlson MO, 712-123-4567\n',
'Frank Fern, 21 S. West St Blippo CA, 901-321-7654\n',
'Mimi Mink, 13 Arbor St Draft NY, 204-777-9631']
[['Carl Arm', '123 Malt Rd Carlson MO', '712-123-4567'],
['Frank Fern', '21 S. West St Blippo CA', '901-321-7654'],
['Mimi Mink', '13 Arbor St Draft NY', '204-777-9631']]
Mimi Mink
13 Arbor St Draft NY
Frank Fern
21 S. West St Blippo CA

From there you can expand to updating/editing and saving your data. Note that the reason to keep things in lists is so you can change data elements.

This article has been dead for over six months. Start a new discussion instead.