Home > Back-end >  How to extract first string between special character from txt file python
How to extract first string between special character from txt file python

Time:01-03

I have a list of emails and passwords divided by : which are stored in myfile.txt file in application location path.

Now each email and password are stored in one line for each account.

Now I need python to extract from first line email and then other method to extract the passwords.

Here is the formatted text:

[email protected]:pass01
[email protected]:pass02
[email protected]:pass03
[email protected]:pass04

MY CODE:

self._emailLoaded = open("./accounts.txt", "r").read().splitlines()
_email = self._emailLoaded ([0])
_password = self._emailLoaded ([1])

I need to email gets the first _email from first line and next if it is called it pick up the next line and next email; the same for _password.

CodePudding user response:

Implement a generator that opens the file, reads one line at a time, splits the line and yields the two constituent parts. Something like this:

FILENAME = 'myfile.txt'

def parse(filename):
    with open(filename) as data:
        for line in data:
            yield line.rstrip().split(':')

for email, password in parse(FILENAME):
    print(f'{email=} {password=}')

Output:

email='[email protected]' password='pass01'
email='[email protected]' password='pass02'
email='[email protected]' password='pass03'
email='[email protected]' password='pass04'

CodePudding user response:

Here's one way you can extract the first string between special characters from a text file in Python:

Copy code import re

def extract_string(file): with open(file, 'r') as f: text = f.read()

# Extract the first string between special characters
result = re.search(r'[^<]*(.*?)[^>]*', text).group(1)
return result

extract_string('text.txt') This function uses the re module to search the text for a pattern that matches any characters that are not '<' or '>', followed by a group of any characters (.*?), followed by any characters that are not '<' or '>'. The group(1) method is used to extract the characters that are matched by the group.

This function assumes that the special characters are '<' and '>', and that the string you want to extract is between the first occurrence of these characters in the text. If the special characters or the position of the string you want to extract are different, you will need to modify the regular expression accordingly.

Regenerate response

CodePudding user response:

You can use a Regex method with this pattern (.*)@.*:(.*) The parentheses means the text that fit in will be stored.

import re
m = re.search(yourText, '(.*)@.*:(.*)')
email = m.group(0)
passw = m.group(1)
  • Related