Input string and Search it inside a file Python - python

I am a newbie I am trying to implement a code where if I type text it will look inside the file and will say if there's something matched or not if doesn't matched anything it will display no record however this below code is not giving the right output any idea thank you very much in advance
input = raw_input("Input Text you want to search: ")
with open('try.txt') as f:
found = False
if input in f:
print "true"
found = True
if not found:
print('no record!')

In order to match a string against the text from the file, you need to read the file:
with open('try.txt') as f:
data = f.read()
Then to check if a string is found in the file, check like this:
if input_ in data:
pass
Also, two tips:
1) Indent your code correctly. Use four spaces for every level of indentation.
2) Don't use reserved keywords to name your variables. Instead of input, use input_ or something else.

You are not actually reading the file, try something like file_content = f.read() and then do a if input in file_content.

This should print "true" if found or "no record!" for not found
I've not included your boolean "found" variable because it's not used.
First the file data is read into "data" variable as a string then we perform a check with in operator
input = raw_input("Input Text you want to search: ")
with open('try.txt', 'r') as myfile:
data=myfile.read()
if input in data:
print "true"
else:
print('no record!')

Related

Is there any way to use a .txt as an input?

name = input("Whats your name?: ")
Can I use for example my .txt that is in the same directory on the input 'name'?
I tried the code bellow /
with open(name.txt, "r") as file:
file.readlines()
But its not working :(
It's a bit unclear what you want exactly. I think you want the variable name to be a name taken from a textfile.
with open("name.txt", "r") as file:
name = file.readline().strip()
print(name)
It works by opening up the file name.txt for reading as text, then it reads the first line, strip() is used to remove any spaces or newlines, and it is stored in the variable name.
There is no need to call input().
Be sure to read the tutorial on input and output.

Read next line in Python

I am trying to figure out how to search for a string in a text file, and if that string is found, output the next line.
I've looked at some similar questions on here but couldn't get anything from them to help me.
This is the program I have made. I have made it solely to solve this specific problem and so it's also probably not perfect in many other ways.
def searcher():
print("Please enter the term you would like the definition for")
find = input()
with open ('glossaryterms.txt', 'r') as file:
for line in file:
if find in line:
print(line)
So the text file will be made up of the term and then the definition below it.
For example:
Python
A programming language I am using
If the user searches for the term Python, the program should output the definition.
I have tried different combinations of print (line+1) etc. but no luck so far.
your code is handling each line as a term, in the code below f is an iterator so you can use next to move it to the next element:
with open('test.txt') as f:
for line in f:
nextLine = next(f)
if 'A' == line.strip():
print nextLine
If your filesize is small, then you may simply read the file by using readlines() which returns a list of strings each delimited by \n character, and then find the index of the selected word, and the print the item at position + 1 in the given list.
This can be done as:
def searcher():
print("Please enter the term you would like the definition for")
find = input()
with open("glossaryterms.txt", "r") as f:
words = list(map(str.strip, f.readlines()))
try:
print(words[words.index(find) + 1])
except:
print("Sorry the word is not found.")
You could try it Quick and dirty with a flag.
with open ('glossaryterms.txt', 'r') as file:
for line in file:
if found:
print (line)
found = False
if find in line:
found = True
It's just important to have the "if found:" before setting the flag. So if you found your search term next iteration/line will be printed.
In my mind, the easiest way would be to cache the last line. This means that on any iteration you would have the previous line, and you'd check on that - keeping the loop relatively similar
For example:
def searcher():
last_line = ""
print("Please enter the term you would like the definition for")
find = input()
with open ('glossaryterms.txt', 'r') as file:
for line in file:
if find in last_line:
print(line)
last_line = line

Trying to read certain text from a file that has strange characters. (Python)

Hello I'm trying to grab data from a keyword in a text document as a project, I am able to do this using this code. I am very new to python and im not sure where to start to troubleshoot this issue.
data_file = open("test.txt", "r")
Keyword = raw_input("Please enter the keyword: ")
go = False
start = Keyword
end = "[+][+]"
with open("test.txt") as infile:
for line in infile:
line = line.strip()
if start in line: go = True
elif end in line:
go = False
continue
if go:
print(line)
This code works great for a sample text document like
Something Something Something Something
Something Something Something Something
Something Keyword:
Data
Data
Data
Data
End
Something
However i run into an issue when trying to read from a file that has strange characters. for example:
2015/08/14 15:48:30 OUT:
2015/08/14 15:48:30 OUT:
PQ=
(3< ’’aÈ©ÿY˜ü â [+][+]52
2015/08/14 15:48:31:IN[+]53[+][+]101[+]-1[+] **Keyword** ,SHOWALL
**data**
**data**
**data**
**data**
**data**
**data**
**data**
end
Since the goal is to read from this text document and just print out the words in between the Keyword and End. it will not execute if it has these characters in them. and for the project I can not remove these characters it just has to be able to read through the document and find the keyword and print out whats in between.
Any ideas on how i can read from a text document that has these strange characters with it processing it correctly rather than just crashing.
First you need to open the file in binary mode. You could then use a regular expression to extract all the text between your entered keyword and "end". Whole words could then be extracted using another regular expression:
import re
with open("input.txt", "rb") as f_input:
start_token = raw_input("Please enter the start keyword: ")
end_token = raw_input("Please enter the end keyword: ")
reText = re.search("%s(.*?)%s" % (re.escape(start_token), re.escape(end_token)), f_input.read(), re.S)
if reText:
for word in re.findall(r"\b\w+\b", reText.group(1)):
print word
else:
print "not found"
For your example text this would display:
SHOWALL
data
data
data
data
data
data
data
Or if you just want all of the text between the two points, print reText.group(1) instead of the for loop.
Updated: added support for a variable end token.
The file contains binary content so it should be opened in binary mode
You can do this by doing
data_file = open("test.txt", "rb")

Checking data from a text file

I've been trying to create a program that takes an input and checks to see whether that input is in some text from a file. My end goal is to create a user login GUI, but I will not show the code for the GUI here as there is quite a lot.
I need to work out how to compare text from an input and from the file.
This is my code so far
def check(entry):
search = open('password.txt', 'r')
if str(entry) in str(search):
return (entry, "Word found")
else:
return entry, ("Word not found")
with open('password.txt', 'r') as text:
print (text.read())
while True:
entry=input("\nSearch for word: ")
print(check(entry))
When I run the code it will say that 1, 2, 5 and 12 are all in the text but none of the words that are in text are confirmed.
If anyone could help it would be appreciated, thanks.
Ignoring the security bad ideas covered in another comment, str(search) doesn't work like you think it does. If you print it, you should see something like:
<open file 'password.txt', mode 'r' at 0x0000000001EB2810>
which is a description of the object you created with the open function. You need to read the file into a string first with the .read() method.

Python search string value from file

I'm trying to create a python script to look up for a specific string in a txt file
For example I have the text file dbname.txt includes the following :
Level1="50,90,40,60"
Level2="20,10,30,80"
I will need the script to search for the user input in the file and print the output that equals that value Like :
Please enter the quantity : 50
The level is : Level1
I am stuck in the search portion from the file ?
any advise ?
Thanks in advance
In these sorts of limited cases, I would recommend regular expressions.
import re
import os
You need a file to get the info out of, make a directory for it, if it's not there, and then write the file:
os.mkdir = '/tmp'
filepath = '/tmp/foo.txt'
with open(filepath, 'w') as file:
file.write('Level1="50,90,40,60"\n'
'Level2="20,10,30,80"')
Then read the info and parse it:
with open(filepath) as file:
txt = file.read()
We'll use a regular expression with two capturing groups, the first for the Level, the second for the numbers:
mapping = re.findall(r'(Level\d+)="(.*)"', txt)
This will give us a list of tuple pairs. Semantically I'd consider them keys and values. Then get your user input and search your data:
user_input = raw_input('Please enter the quantity: ')
I typed 50, and then:
for key, value in mapping:
if user_input in value:
print('The level is {0}'.format(key))
which prints:
The level is Level1
Use the mmap module, the most efficient way to do this hands down. mmap doesn't read the entire file into memory (it pages it on demand) and supports both find() and rfind()
with open("hello.txt", "r+b") as f:
# memory-map the file, size 0 means whole file
mm = mmap.mmap(f.fileno(), 0)
position = mm.find('blah')

Categories

Resources