Saturday, March 23, 2019

Finding string from a file

I would like to share how to some string of a file by using python script.It's just like when we are searching some string from a text file.

Purpose of this script:
The text file contains password of day, in other word, meaning everyday contains different password according to different date.
Example 1:
Prerequisite:
You should obtain a text file which contain many data.

Text File:





Source code
```
#python 2
import sys
substring = raw_input("enter your string (Ex:20180810): ")

count =0  
for line in open('POD_RDKB_10Year.txt'):
    #if ("") in line:
    if substring in line:
 line = line.strip()
        count +=1
        print (line)
if count==0:
    print ("string not found")  

```

```
# python3
import sys
substring = input ("enter your string (Ex:20180810):: ")

count =0  
for line in open('POD_RDKB_10Year.txt'):
    #if ("") in line:
    if substring in line:
       line = line.strip()
 
       count +=1
       print (line)
if count==0:
    print ("string not found")

```

  Output
enter your string (Ex:20180810):: 20180810
20180810        eui7pieralWHvt9p


Example2
If you like to used another way, finding keyword written in source code without input it, please refer this source code as below:

```

# -*- coding: utf-8 -*-
#
import sys

string = "Hello Agnosticdev, I love Tutorials"
substring = "Agnosticdev"

# Straight forward approach for Python 2.7 and Python 3.6
# Executes the conditional statement when the substring is found
if substring in string:
 print ("Your substring was found!")



# Alternative Approach

# Use the find method in Python 2.7 or Python 3.6
if string.find(substring) is not -1:
 print("Python found the substring!")
else:
 print("Python did NOT find the substring!")

``` 

Example3

Search your file and export to a new file

```

#support python2 and 3

def find(substr, infile, outfile):
  with open(infile) as a, open(outfile, 'w') as b:
   for line in a:
    if substr in line:
     b.write(line + '\n')
     print(line + '\n')
 
# Example usage:
find('20181109', 'POD_RDKB_10Year.txt', 'b.txt')

``` 

No comments:

Post a Comment