Read text file values and assign it to each value to variable

3862 views python
3

I want to read text file and find the words that starts with 56 in below text and pass each word to a variable and pass to a python file as a parameters.

My sample text file content -

51:40:2e:c0:01:c9:53:e8
56:c9:ce:90:4d:77:c6:03
56:c9:ce:90:4d:77:c6:07
51:40:2e:c0:01:c9:54:80
56:c9:ce:90:12:b4:19:01
56:c9:ce:90:12:b4:19:03

I like to pass to python file as

mytestfile.py <56:c9:ce:90:4d:77:c6:03> <56:c9:ce:90:4d:77:c6:07> <56:c9:ce:90:12:b4:19:01> <56:c9:ce:90:12:b4:19:03>

Thanks in advance

answered question

Are you sure that you need to pass parameters for mytestfile.py in a such way?

I mean as a variable like mytestfile.py var1 var2 var3 var4. I want to assign it to variable that should increase for each value

1 Answer

4

So this code prints string of required variables:

# a.py
with open('file.txt') as f:
    result = ' '.join(map(lambda x: f'<{x}>',
                          filter(lambda x: x.startswith('56'),
                                 map(str.strip, f))))
    print(result)

Output:

<56:c9:ce:90:4d:77:c6:03> <56:c9:ce:90:4d:77:c6:07> <56:c9:ce:90:12:b4:19:01> <56:c9:ce:90:12:b4:19:03>

You can pass result of this program using pipe to some another python program. For example:

# b.py  
import sys

print(sys.stdin.readlines())

Than just type in shell:

python3 a.py | python3 b.py

Output:

['<56:c9:ce:90:4d:77:c6:03> <56:c9:ce:90:4d:77:c6:07> <56:c9:ce:90:12:b4:19:01> <56:c9:ce:90:12:b4:19:03>\n']

posted this

Have an answer?

JD

Please login first before posting an answer.