Python - Scan File and Extract Data from Sticky Tags

Asked

Viewed 106 times

-2

Good morning, you guys!

So, I’m starting in python and I have a question regarding string.

I have a file with information and need to extract some data from it and move to another file. Basically, I have the tag that refers to the given, example:

"gatewayTransactionId": "DATA I NEED", "amountInCents": DATA I NEED.

How can I do that?

Is it possible to assign tags to a variable and then scan the string after that tag to the limiter? The goal is to create a code where I can get the data of 1 or 10 tags.

Obs.: Tags are always static, what will change is the result, always.

They can give me a north?

Below follows the code I started, where I see the file and look for the first tag (gatewayTransactionId).

in_file = "logfile.txt"
out_file = "file_with_extractedlines.txt"
search_for = "gatewayTransactionId"
str1='string'

line_num = 0
lines_found = 0

with open(out_file, 'w') as out_f:
    with open(in_file, "r") as in_f:
        for line in in_f:
            line_num += 1
            if search_for in line:
                lines_found += 1
                str1=search_for
                print("Os dados foram salvos no arquivo  "file_with_extractedlines.txt")
                print("Found String: {}...".format(str1))
                out_f.write(line)

        print("Found {} lines...".format(lines_found))

1 answer

0

From what I understand, you want to have a set of tags and from these tags, check if in each row of a respective file they exist and then write those lines in another file. This can be easily done with the function filter python.

fileToRead = "read.txt"
fileToWrite = "write.txt"

lines = open(fileToRead, 'r').split('\n')

tags = ["gatewayTransactionId", "amountInCents"];

parseLines = lambda line: any([tag in line for tag in tags])
dataToWrite = list(filter(parseLines, lines))

writableFile = open(fileToWrite, 'w')
writableFile.write('\n'.join(dataToWrite))
  • Speak, Peter! So that’s about it, I want to identify the tags and get what’s shown from it. For example: Line 1: gatewayTransactionId: example123. In this example, I want to identify the gatewayTransactionId tag, save the tag and its contents in another file, in this case, the exemple123. .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.