Search code examples
pythonstringtexttrimtruncation

Python text file trim colon


I've a text file that looks like this

firstname:lastname:123456789
somename:somelastname:12312456456
...

I want to put each name, lastname, and id into it's own variable.

This is how I made it so far.

with open("somefile.txt", 'r') as a:
    phonebook = a.readlines()

l = 0
while (len(phonebook) < l+1):
    firstname = 
    lastname =
    number =

    l++

And got stuck on the trimming part.


Solution

  • Just store the data in a list, a sublist for each line split into firat name, last name and id.

    with open("somefile.txt", 'r') as f:
        data = [line.strip().split(":") for line in f]
    

    You could also use a dict but there would be no real advantage unless you wanted to do lookups by name but even then names would need to be unique, if you just want to use each piece of data in a loop and not store all then use as your iterate:

    with open("somefile.txt", 'r') as f:
        for line in f:
           fn, ln , _id = line.strip().split(":")