So I essentially have an accounts.txt file with accounts I created which look like this:

Richard:Milo:[email protected]:0495612970
Adrian:Clark:[email protected]:0490714484
Michael:Robinson:[email protected]:0446088017
Julio:Lucas:[email protected]:0454710033

As you can see they are in the format FirstName:LastName:Email:Phone

Put simply, what I want my python script to do is read each line, return the first name, last name, email, and phone on each line as the "email", "first_name", "last_name", and "phone" variables and then delete that line entirely then move on to the next line, do the exact same, then delete the line, etc etc. I already have the loop down pat it's just returning one part of each line which is giving me difficulty.

Here is my current python code:

submit_count = input('\nEnter Desired Number of Entries: ')

chrome_options = webdriver.ChromeOptions()
driver = webdriver.Chrome(chrome_options=chrome_options)

def enterraffle():

    email = #NOT SURE HOW TO GET THE EMAIL FROM ACCOUNTS.TXT HERE
    first_name = #NOT SURE HOW TO GET THE FIRST NAME FROM ACCOUNTS.TXT HERE
    last_name = #NOT SURE HOW TO GET THE LAST NAME FROM ACCOUNTS.TXT HERE
    phone = #NOT SURE HOW TO GET THE PHONE FROM ACCOUNTS.TXT HERE

    driver.get(‘Login URL’)

    driver.find_element_by_xpath('//*[@id="email"]').send_keys(email)
    driver.find_element_by_xpath('//*[@id="password"]').send_keys(‘password123’)

    print('{}/{} Successful Raffle Entries ({} {}:{})'.format(i, submit_count, first_name, last_name, email))
    with open("entries_nl.txt", "a") as f:
        f.write(first_name + ":" + last_name + ":" + email + ":" + phone + ":" + "\n")
        f.close()

    time.sleep(2)

    #DELETE THAT LINE FROM ACCOUNTS.TXT HERE

    driver.delete_all_cookies()

for i in range(int(submit_count)):
        enterraffle()

Any help is appreciated!

2 Answers

0
Wanming Zhang On Best Solutions
lines = []
fields = ['first_name', 'last_name', 'email', 'phone']
with open('accounts.txt') as fp:
    for line in fp:
    values = [x.strip() for x in line.split(':')]
    lines.append(dict(zip(fields, values)))
0
Devesh Kumar Singh On

You can use the csv.reader module to read your csv file.

import csv

#Open the file
lines = []
with open('accounts.txt') as fp:

    #Create a csv reader on the file
    reader = csv.reader(fp, delimiter=":")
    #Iterate through each row
    for row in reader:
        lines.append(row)

print(lines)

The output will be

[
['Richard', 'Milo', '[email protected]', '0495612970'], 
['Adrian', 'Clark', '[email protected]', '0490714484'], ['Michael', 'Robinson', '[email protected]', '0446088017'], 
['Julio', 'Lucas', '[email protected]', '0454710033']
]

So the first email will be lines[0][2]

Then to delete the contents of the file, just open it in w+ mode

#Open the file in w+ to delete all rows
filename = "accounts.txt"
f = open(filename, "w+")
f.close()

You can then use this output to your enterraffle() function