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

Time:10-24

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

CodePudding user response:

data = file_to_open.readlines()

for line in data:
    print(line.split(':')[-1])

CodePudding user response:

file_save = open("adresses.txt", 'a')

with open('data.txt', 'r') as file_to_open:
    data = file_to_open.read().split("\n")  # first split into lines
    addresses = []  # initialize address list
    for line in data:
        address = line.split(":")[-1]  # get last element splitted by ":"
        addresses.append(address)  # save to addresses
    file_save.write("\n".join(addresses))  # one new line between each entry

file_save.close()  # this needs to be file_save not file_to_open

CodePudding user response:

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()

CodePudding user response:

Using csv and a comprehension:

import csv 
with open('data.txt') as rf, open('address.txt', 'w') as wf:
    wf.writelines(a[-1]   '\n' for a in csv.reader(rf, delimiter=':'))

Or without csv:

with open('data.txt') as rf, open('address.txt', 'w') as wf:
    wf.writelines(a.split(':')[-1] for a in rf)
  • Related