Search code examples
pythonstringsplitdelimiter

Read lines from file and split line on last delimiter in Python and save it to another file


I have a file named data.txt which contains names, mails and addresses separated by a colon. It looks like this:

first_name1:last_name1:[email protected]:address1
first_name2:last_name2:[email protected]:address2
first_name3:last_name3:[email protected]:address3
first_name4:last_name5:[email protected]:address4
first_name5:last_name6:[email protected]:address5
first_name6:last_name7:[email protected]:address6
first_name7:last_name8:[email protected]:address7

I would like to read only addresses and store it in separate file called addresses.txt (one address in a line). I tried such a code:

#name of file to store addresses
file_save = open("adresses.txt", 'a')

with open('data.txt', 'r') as file_to_open:
    data = file_to_open.read().rsplit(":",1)

    file_save.write(data[-1])

    print(data) #for testing only

file_to_open.close()

BUT it gives me such a result:

['first_name1:last_name1:mail1:address1\nfirst_name2:last_name2:mail2:address2\nfirst_name3:last_name3:mail3:address3\nfirst_name4:last_name5:mail4:address4\nfirst_name5:last_name6:mail5:address5\nfirst_name6:last_name7:mail6:address6\nfirst_name7:last_name8:mail7', 'address7']

What i have done wrong?

I try to make it something like this:

address1
address2
address3
...

Please help


Solution

  • You could try using the split method on each line of data

    file_save = open("adresses.txt", 'a')
    
    with open('data.txt', 'r') as file_to_open:
        data = file_to_open.readlines();
        for address in data:
            file_save.write(address.split(":")[-1])
    
    file_to_open.close()