I have below working code which works fine, but just looking way around if there is an another elegant way of doing this, because here i'm using else condition to print the last line or dataBlock to be printed.
Note: mydudalt1
and mydudalt2
are the host names
My data File:
$ cat mydata_test.txt
-- mydudalt1 --
192.168.2.40; // udalt-sanjose
192.168.2.56; // udalt-sj1
192.168.98.71; // udalt-japan
192.168.2.146; //udalt-sj-fwd1
-- mydudalt2 --
199.43.4.70; // udalt-chelms
192.168.2.56; // udalt-sj1
192.168.98.71; // udalt-japan
My Working code:
#!/grid/common/pkgs/python/v3.6.1/bin/python3
dataBlock = ''
with open('mydata_test.txt', 'r') as frb:
for line in frb:
line = line.strip("\n")
if line.startswith('--'):
if "japan" in dataBlock:
print(dataBlock)
dataBlock = ''
dataBlock = dataBlock + line
elif "japan" in line:
dataBlock = dataBlock + line
else:
print(dataBlock + line)
Resulted Output:
-- mydudalt1 -- 192.168.98.71; // udalt-japan
-- mydudalt2 -- 192.168.98.71; // udalt-japan
3 Answers 3
If "japan"
only appears once in each section, you can store the startswith
line, and simply print out the desired output immediately when the matching line is found:
for line in frb:
line = line.strip("\n")
if line.startswith("--"):
prefix = line
if "japan" in line:
print(prefix + line)
-
\$\begingroup\$ AJNeufeld, this looks to be neat and promising +1, thnx \$\endgroup\$Karn Kumar– Karn Kumar2019年08月06日 03:14:31 +00:00Commented Aug 6, 2019 at 3:14
Unless there is an indentation issue,
dataBlock = ''
dataBlock = dataBlock + line
can be written:
dataBlock = line
-
\$\begingroup\$ Josay, that will not do the job because if i will use
dataBlock = line
instead ofdataBlock = dataBlock + line
then it will not print host names. +1 for the throwing an idea \$\endgroup\$Karn Kumar– Karn Kumar2019年08月06日 03:15:28 +00:00Commented Aug 6, 2019 at 3:15
A quick Answer [Should not be used in PRODUCTION]
I mainly try to answer your concern over how to avoid "for-else" to handle last edge case, and haven't reviewed much of rest of code.
#!/grid/common/pkgs/python/v3.6.1/bin/python3
block_start_identifier = "--"
search_word = "japan"
data_block = []
block_satisfied = False
with open('mydata_test.txt', 'r') as frb:
for line in frb.readlines():
if line.startswith(block_start_identifier):
# Print previous blocks
if block_satisfied:
print("".join(data_block))
# Reset data blocks
data_block = []
block_satisfied = False
data_block.append(line)
elif search_word in line:
data_block.append(line)
block_satisfied = True
# Flush the block again as needed to handle last case
if block_satisfied:
print("".join(data_block))
```
-
\$\begingroup\$ kushj, thnx for the answer. +1 for the approach around. \$\endgroup\$Karn Kumar– Karn Kumar2019年08月06日 03:14:00 +00:00Commented Aug 6, 2019 at 3:14
mydudalt
blocks have more than one JAPAN Ids in them? \$\endgroup\$mydudalt1
andmydudalt2
are the host names. \$\endgroup\$