else statement keep looping print 'not found' in python [duplicate] - python

This question already has answers here:
print if else statement on python
(2 answers)
Closed 8 years ago.
I want to print not found ONCE if in the text file not found a string. But the string keeps printing not found following how many line in the file. Its because it read all the line. So it printing all not found based on how many lines in it. Is there other way to do it?
import os
f = open('D:/Workspace/snacks.txt', "r");
class line:
for line in f.readlines():
if line.find('chocolate') != -1:
print "found ", line
elif line.find('milkshake') != -1:
print "found ", line
else:
print "not found"

Are you looking for the break statement in python? As the name reflects, this statement simply breaks you out of the loop.
Eg:
for line in f.readlines():
if line.find('chocolate') != -1:
print "found ", line
elif line.find('milkshake') != -1:
print "found ", line
else:
print "not found"
break

First, remove this line - class line:. Re-indent the lines below it.
Two things should help you:
break clause
else clause in for loop
Please read the official tutorial on control flow.
And then the code becomes like this
>>> for line in f.readlines():
... if line.find('chocolate') != -1 or line.find('milkshake') != -1:
... print "found ", line
... break
... else:
... print "not found"
...
not found

Related

How to get exit code from Python?

I have a python code. I use cmd file to execute my python code. In the cmd file, I am going to get errorlevel from my python code.
infile = "FeatureByte.txt"
Array = ["6J", "yB", "ss", "11"]
with open(infile, "r") as input_file:
output_list = []
for rec in input_file.read().splitlines():
rec = rec[:-3]
FBlist = [rec[i:i+2] for i in range(0, len(rec), 2)]
output_list.append(FBlist)
print(output_list)
FBlist_set = set(FBlist)
Array_set = set (Array)
if Array_set & FBlist_set:
print ("Found")
exit(0)
else:
print ("Not Found")
exit(1)
This is my cmd file :
set logfile=C:\Users\Log.txt
set PYTHONPATH="C:\Users\AppData\Local\Programs\Python\Python37-32"
set PYTHONEXE="%PYTHONPATH%\Python -B"
"C:\Users\AppData\Local\Programs\Python\Python37-32\python.exe" -B C:\Users\Desktop\Pyth.py
echo %ERRORLEVEL% >> "%logfile%"
From these both code, I always get 1 inside my Log.txt file.
I think the problem is in this line:
if Array_set & FBlist_set:
print ("Found")
exit(0)
Change it to:
if Array_set and FBlist_set:
print ("Found")
exit(0)
else:
print ("Not Found")
exit(1)
& that you use is bitwise operator and not the logical operator and. Because of which the if condition fails and you get to the else part which returns exit(1) to you as status code.
The noticed return of 0 and 1 as commented response to roganjosh and Devanshu Misra's solution is because your If-statement is written to do so due to a indentation typo (perhaps lacking an IDE editor?).
You have:
if Array_set & FBlist_set:
print ("Found")
exit(0)
else:
print ("Not Found")
exit(1)
This code always exits with "1". In some cases it exits first with "0" but followed with "1".
It should be:
if Array_set and FBlist_set:
print ("Found")
exit(0)
else:
print ("Not Found")
exit(1) # <--- this exit(1) should be inside the "else" clause.
No need here to point out the use of "&" instead of "and" as this was addressed earlier by roganjosh. Anyway, keep an eye on the changed color of "and". Its blue and means that it became a selection participant in the if-statement.
... but watch out for the result FBlist = [''] because it will trigger a false positive FBlist_set and thus exit the wrong way.
Enjoy ;-)

Openning all text file & getting a string in python [duplicate]

I want to check if a string is in a text file. If it is, do X. If it's not, do Y. However, this code always returns True for some reason. Can anyone see what is wrong?
def check():
datafile = file('example.txt')
found = False
for line in datafile:
if blabla in line:
found = True
break
check()
if True:
print "true"
else:
print "false"
The reason why you always got True has already been given, so I'll just offer another suggestion:
If your file is not too large, you can read it into a string, and just use that (easier and often faster than reading and checking line per line):
with open('example.txt') as f:
if 'blabla' in f.read():
print("true")
Another trick: you can alleviate the possible memory problems by using mmap.mmap() to create a "string-like" object that uses the underlying file (instead of reading the whole file in memory):
import mmap
with open('example.txt') as f:
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if s.find('blabla') != -1:
print('true')
NOTE: in python 3, mmaps behave like bytearray objects rather than strings, so the subsequence you look for with find() has to be a bytes object rather than a string as well, eg. s.find(b'blabla'):
#!/usr/bin/env python3
import mmap
with open('example.txt', 'rb', 0) as file, \
mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
if s.find(b'blabla') != -1:
print('true')
You could also use regular expressions on mmap e.g., case-insensitive search: if re.search(br'(?i)blabla', s):
As Jeffrey Said, you are not checking the value of check(). In addition, your check() function is not returning anything. Note the difference:
def check():
with open('example.txt') as f:
datafile = f.readlines()
found = False # This isn't really necessary
for line in datafile:
if blabla in line:
# found = True # Not necessary
return True
return False # Because you finished the search without finding
Then you can test the output of check():
if check():
print('True')
else:
print('False')
Here's another way to possibly answer your question using the find function which gives you a literal numerical value of where something truly is
open('file', 'r').read().find('')
in find write the word you want to find
and 'file' stands for your file name
if True:
print "true"
This always happens because True is always True.
You want something like this:
if check():
print "true"
else:
print "false"
Good luck!
I made a little function for this purpose. It searches for a word in the input file and then adds it to the output file.
def searcher(outf, inf, string):
with open(outf, 'a') as f1:
if string in open(inf).read():
f1.write(string)
outf is the output file
inf is the input file
string is of course, the desired string that you wish to find and add to outf.
Your check function should return the found boolean and use that to determine what to print.
def check():
datafile = file('example.txt')
found = False
for line in datafile:
if blabla in line:
found = True
break
return found
found = check()
if found:
print "true"
else:
print "false"
the second block could also be condensed to:
if check():
print "true"
else:
print "false"
Two problems:
Your function does not return anything; a function that does not explicitly return anything returns None (which is falsy)
True is always True - you are not checking the result of your function
.
def check(fname, txt):
with open(fname) as dataf:
return any(txt in line for line in dataf)
if check('example.txt', 'blabla'):
print "true"
else:
print "false"
How to search the text in the file and Returns an file path in which the word is found
(Как искать часть текста в файле и возвращять путь к файлу в котором это слово найдено)
import os
import re
class Searcher:
def __init__(self, path, query):
self.path = path
if self.path[-1] != '/':
self.path += '/'
self.path = self.path.replace('/', '\\')
self.query = query
self.searched = {}
def find(self):
for root, dirs, files in os.walk( self.path ):
for file in files:
if re.match(r'.*?\.txt$', file) is not None:
if root[-1] != '\\':
root += '\\'
f = open(root + file, 'rt')
txt = f.read()
f.close()
count = len( re.findall( self.query, txt ) )
if count > 0:
self.searched[root + file] = count
def getResults(self):
return self.searched
In Main()
# -*- coding: UTF-8 -*-
import sys
from search import Searcher
path = 'c:\\temp\\'
search = 'search string'
if __name__ == '__main__':
if len(sys.argv) == 3:
# создаем объект поисковика и передаем ему аргументы
Search = Searcher(sys.argv[1], sys.argv[2])
else:
Search = Searcher(path, search)
# начать поиск
Search.find()
# получаем результат
results = Search.getResults()
# выводим результат
print 'Found ', len(results), ' files:'
for file, count in results.items():
print 'File: ', file, ' Found entries:' , count
If user wants to search for the word in given text file.
fopen = open('logfile.txt',mode='r+')
fread = fopen.readlines()
x = input("Enter the search string: ")
for line in fread:
if x in line:
print(line)
found = False
def check():
datafile = file('example.txt')
for line in datafile:
if blabla in line:
found = True
break
return found
if check():
print "true"
else:
print "false"
found = False
def check():
datafile = file('example.txt')
for line in datafile:
if "blabla" in line:
found = True
break
return found
if check():
print "found"
else:
print "not found"
Here's another. Takes an absolute file path and a given string and passes it to word_find(), uses readlines() method on the given file within the enumerate() method which gives an iterable count as it traverses line by line, in the end giving you the line with the matching string, plus the given line number. Cheers.
def word_find(file, word):
with open(file, 'r') as target_file:
for num, line in enumerate(target_file.readlines(), 1):
if str(word) in line:
print(f'<Line {num}> {line}')
else:
print(f'> {word} not found.')
if __name__ == '__main__':
file_to_process = '/path/to/file'
string_to_find = input()
word_find(file_to_process, string_to_find)
"found" needs to be created as global variable in the function as "if else" statement is out of the function. You also don't need to use "break" to break the loop code.
The following should work to find out if the text file has desired string.
with open('text_text.txt') as f:
datafile = f.readlines()
def check():
global found
found = False
for line in datafile:
if 'the' in line:
found = True
check()
if found == True:
print("True")
else:
print("False")

Python switching the display based on input using If, Else

I want to display print text based on my Input value using IF/Else or Switch. And Also let me know how to use switch case for below code.
# OnButtonOK after clicking it, display the input value
def OnButtonOK(self):
Input = self.entrytext.get()
# self.text.insert(END, Input + '\n')
# self.scroll.config(Input = self.text.yview)
print Input
useroption = atoi(Input)
# self.OnButtonClick();
if (useroption == 1):
print "input is output"
self.SubMenu1();
else:
print "Error:Invalid"
return;
def SubMenu1(self):
print 'SubMenu1'
return;
def SubMenu2(self):
print 'SubMenu2'
return;
def SubMenu3(self):
print 'SubMenu3'
return;
I am able to print only else part:
if (useroption == 1):
print "input is output"
self.SubMenu1();
else:
print "Error:Invalid"
Let me know where exactly i am going wrong.
I think you have indentation problems in your code:
Python use 4 spaces(you can use 1 space but 4 is good practice) indentation language. Means if/else statement will be like this:
if a == 1:
print("A = 1") # 4 spaces w.r.t to above statement
elif a == 2:
print("A = 2")
elif a ==3:
print("A = 4")
else:
print("A = pta nahi")
you can use above if/else statements as a switch case and also your indentation problem will be solved
It's a simple beginner's mistake, you're indenting it worng:
if (useroption == 1):
print "input is output"
self.SubMenu1();
else:
print "Error:Invalid"
should be
if (useroption == 1):
print "input is output" # You had an indent too many here
self.SubMenu1();
else:
print "Error:Invalid"
Python is indentation sensitive; too many or too few indentations will break your code.

How to redirect the output of print statement of (if-else) to a text file in Python

I have this piece of code, and print the output to a txt file.
However whenever I open a file,
f=open("out.txt",'w') it shows unexpected indent. I guess I am placing the line of code to a wrong position.
Can anyone help.
if(cp<0):
print("No Common Predecessor")
elif (posa < posb):
if(posa<0):
posa=0
print("Common Predecessor: %s" %n[posa])
else:
if(posb < 0):
posb=0
print("Common Predecessor: %s" %m[posb])
In Python3 the output redirection is as simple as
print(....., file = open("filename",'w'))
Refer the docs
In your particular case you can even use the with open syntax as in
if(cp<0):
print("No Common Predecessor")
elif (posa < posb):
if(posa<0):
posa=0
with open('out.txt','w')as f:
print("Common Predecessor: %s" %n[posa])
f.write("Common Predecessor: %s" %n[posa])
else:
if(posb < 0):
posb=0
with open('anotherout.txt','w')as f:
print("Common Predecessor: %s" %m[posb])
f.write("Common Predecessor: %s" %m[posb])
Note - It is always better to use 'a' (append) instead of 'w' incase you are re-executing the program.

Syntax error that I can't figure out

Yes I realize I made a mistake about editing original question out, so here it is again; note that I instantly asked another question because I previously had this area in another project I practiced on that I gave up on with the same issue and I couldn't figure out how to fix it.
def overwrite():
print "Which save file would you like to overwrite?"
print "Save file 1 contains:" x['name']
print "Save file 2 contains:" y['name']
print "Save file 3 contains:" z['name']
ovw=raw_input()
if ovw.lower() == 1:
write_data({'name':name, 'fname':'ply.json'}, 'ply.json')
elif ovw.lower() == 2:
write_data({'name':name, 'fname':'ply1.json}, 'ply1.json')
elif ovw.lower() == 3:
write_data({'name':name, 'fname':'ply2.json}, 'ply2.json')
else:
print "I don't understand that. Let's try again."
overwrite()
"x" is causing a syntax error on line three and I don't know why.
Well, first of all, the body of the function overwrite() should be indented; but I'm assuming that is a copy-and-paste fault. To fix your specific issue, you need a comma between the arguments for print. It should be:
print "Save file 1 contains:", x['name'] # notice the comma before the x
The same goes for the other print statements.
Also, you have some missing apostrophes/quotes. Where you have 'fname:'ply1.json', it should be 'fname':'ply1.json' (this occurs in two places).
Edit:
If you keep getting "unexpected indent" errors, then it is likely that you are mixing tabs and spaces in the file. (I get this all the time when I switch editors...)
The print statement with x['name'], y['name'] and z['name'] are not concatenated properly to the first part of the string. You should show us the actual errors you're receiving. If x['name'] is a string, the line could be properly written as:
print "Save file 1 contains:" + x['name'] # plus sign
or
print "Save file 1 contains:", x['name'] # comma
And the same for the print statements for y and z
def overwrite():
print "Which save file would you like to overwrite?"
print "Save file 1 contains:" x['name'] # x['name'] part is not concatenated properly to the first part of the string
print "Save file 2 contains:" y['name']
print "Save file 3 contains:" z['name']
ovw=raw_input()
if ovw.lower() == 1:
write_data({'name':name, 'fname':'ply.json'}, 'ply.json')
elif ovw.lower() == 2:
write_data({'name':name, 'fname':'ply1.json'}, 'ply1.json')
elif ovw.lower() == 3:
write_data({'name':name, 'fname':'ply2.json'}, 'ply2.json')
else:
print "I don't understand that. Let's try again."
overwrite()

Categories

Resources