No output on command line python - python

This is my code. when I run it, it simply exits after running. There is nothing printed. Why so ?
def checkString(filename, string):
input = file(filename) # read only will be default file permission
found = False
searchString = string
for line in input:
if searchString in line:
found = True
break
if callfunc == 'initialize':
print listdir() #this will print list of files
print "\n"
for files in listdir():
checkString(files,"hello")
if found:
print "String found"
else:
print "String not found"
input.close()

found is a local name in the function checkString(); it stays local because you don't return it.
Return the variable from the function and store the return value:
def checkString(filename, string):
input = file(filename) # read only will be default file permission
found = False
searchString = string
for line in input:
if searchString in line:
found = True
break
return found
for files in listdir():
found = checkString(files,"hello")
if found:
print "String found"
else:
print "String not found"

You need to modify to:
def checkString(filename, string):
input = file(filename) # read only will be default file permission
found = False
searchString = string
for line in input:
if searchString in line:
found = True
break
input.close()
return found
found = False
if callfunc == 'initialize':
print listdir() #this will print list of files
print "\n"
for files in listdir():
found = found or checkString(files,"hello")
if found:
print "String found"
else:
print "String not found"
This is because in your original found is only in scope within the function checkString

Related

Program not recognizing conditional statements in for loop

I'm trying to print "None" if the input entered by the user is not found in a text file I created. It should also print if the lines if word(s) are found in the text file.
My problem right now is that it is not doing both conditionals. If I were to remove the "line not in user_pass" it would not print anything. I just want the user to be able to know if the strings entered by the user can found in the file and will print that line or "none" if it is not found.
I commented out the ones where I tried fixing my code, but no use.
My code below:
def text_search(text):
try:
filename = "words.txt"
with open(filename) as search:
print('\nWord(s) found in file: ')
for line in search:
line = line.rstrip()
if 4 > len(line):
continue
if line.lower() in text.lower():
print("\n" + line)
# elif line not in text: # the function above will not work if this conditional commented out
# print("None")
# break
# if line not in text: # None will be printed so many times and line.lower in text.lower() conditional will not work
# print("none")
except OSError:
print("ERROR: Cannot open file.")
text_search("information")
I think you need to change for line in search: to for line in search.readlines(): I don't think you're ever reading from the file... Have you tried to just print(line) and ensure your program is reading anything at all?
#EDIT
Here is how I would approach the problem:
def text_search(text):
word_found = False
filename = "words.txt"
try:
with open(filename) as file:
file_by_line = file.readlines() # returns a list
except OSError:
print("ERROR: Cannot open file.")
print(file_by_line) # lets you know you read the data correctly
for line in file_by_line:
line = line.rstrip()
if 4 > len(line):
continue
if line.lower() in text.lower():
word_found = True
print("\n" + line)
if word_found is False:
print("Could not find that word in the file")
text_search("information")
I like this approach because
It is clear where you are reading the file and assigning it to a variable
This variable is then printed, which is useful for debugging
Less stuff is in a try: clause (I like to not hide my errors, but that's not a huge deal here because you did a good job specifying OSError however, what if an OSError occured during line = line.rstrip() for some reason...you would never know!!)
If this helped I'd appreciate if you would click that green check :)
Try this:-
def find_words_in_line(words,line):
for word in words:
if(word in line):
return True;
return False;
def text_search(text,case_insensitive=True):
words = list(map(lambda x:x.strip(),text.split()));
if(case_insensitive):
text = text.lower();
try:
filename = 'words.txt'
with open(filename) as search:
found = False;
for line in search:
line = line.strip();
if(find_words_in_line(words,line)):
print(line);
found = True;
if(not found):
print(None);
except:
print('File not found');
text_search('information');
Didn't really understand your code, so making one on my own according to your requirement.

Python 'with open' print text file

I am trying to add a print to text file for my results as well as the cmd line list that displays. And tried using with open('output.txt', 'w') as f:. Though the code already uses with open(lic) as f:. Can I use multiple "with open" statements? How can I generate a file text printout in addition to the cmd line list?
import time
fips_dict = {}
fips_dict["02000"]="AK"
fips_dict["02013"]="AK, Aleutians East"
fips_dict["02016"]="AK, Aleutians West"
while 1: #repeat forever
count = 0
lic = "//Server/replicated/Userdata/"+raw_input("Account: ")+"/Dmp/LicenseStyle.xml"
print
try: #error handling
with open(lic) as f:
for line in f:
#get and print fips codes and county names
if 'RampEntry' in line:
count += 1
fips_index = line.index('dataValue')+11
code = line[fips_index : fips_index+5]
statecode = line[fips_index : fips_index+2]
if code.isalnum():
print code,fips_dict[code]
elif statecode.isalpha():
print "Entire State of", statecode
print
else:
print "format error in", lic
except IOError: #if file not found
print lic[23:],"not found"
except KeyError: #if no match for FIPS
print "not found"
except:
print "an unexpected error has occured!"
print
now = time.strftime("%c")
print ("%s" % now )
print

IndexError: list index out of range Python error

My command line arguments:
python SearchString.py 10 nee
Argument 1 does not match the length. How should i handle that ?
Error:
File "SearchString.py", line 30, in string_search
search = temp[fieldindex]
IndexError: list index out of range
#!usr/bin/python
import sys
def string_search():
'''
This function search a string in a file through index and gives the result.
:returns: none
:return type: none
:author:XYZ
'''
if len(sys.argv) != 3:
print "Enter Two Arguments Only"
sys.exit()
stringsrch = sys.argv[2]
found = False
file_name = open("passwd", "r")
if sys.argv[1].isdigit():
fieldindex = int(sys.argv[1])-1
else:
print "Enter Integer in 1st Argument"
sys.exit()
#fieldindex = int(sys.argv[1])-1
for store_file in file_name:
temp = store_file.split(":")
search = temp[fieldindex]
if stringsrch in search:
print store_file
found = True
if not found:
print "No String "
string_search()
I think the code depends on how you use it.
search = temp[fieldindex]. From the code, your fieldindex is 9, so you should make sure len(temp) > 9. Or you will get error like what you said.

Python: Get/Scan All Text After a Certain String

I have a text file which I read using readlines(). I need to start extracting data after a keyword in the text file. For example, after the key word Hello World below, I would like to retrieve the value 100 from Blah=100:
Blah=0
Blah=2
Hello World
All the Text
Will be Scan
And Relevant
Info will be
Retrieved Blah=100
I can easily retrieved the information I want from the text file but I need it to start retrieving ONLY after a certain keyword in the textfile, such as after the 'Hello World' above. What I am currently doing is to retrieve the value using .split('='). Thus, I will retrieve all 3 values which are Blah=0, Blah=2 and Blah=100. I only wish to retrieve the value after a keyword in the text file, say 'Hello World', which is the value Blah=100.
There must be a simple way to do this. Please help. Thanks.
There are many ways to do it. Here's one:
STARTER = "Hello World"
FILENAME = "data.txt"
TARGET = "Blah="
with open(FILENAME) as f:
value = None
start_seen = False
for line in f:
if line.strip() == STARTER:
start_seen = True
continue
if TARGET in line and start_seen:
_,value = line.split('=')
break
if value is not None:
print "Got value %d" % int(value)
else:
print "Nothing found"
Here's a slightly pseudo-codish answer- you just need a flag that changes to True once you've found the keyword:
thefile = open('yourfile.txt')
key = "Hello World"
key_found = False
for line in thefile:
if key_found:
get_value(line)
# Optional: turn off key_found once you've found the value
# key_found = False
elif line.startswith(key):
key_found = True
Here's one way, not necessarily the best; I hard-coded the text here, but you could use file.read() to get similar results:
the_text = '''Blah=0
Blah=2
Hello World
All the Text
Will be Scan
And Relevant
Info will be
Retrieved Blah=100
'''
keyword = 'Hello World'
lines = the_text.split('\n')
for line_num, line in enumerate(lines):
if line.find(keyword) != -1:
lines = lines[line_num:]
break
the_value = None
value_key = 'Blah'
for line in lines:
if line.find(value_key) != -1:
the_value = line.split('=',2)[1]
break
if the_value:
print the_value
Example with regex.
reg = re.compile("Hello World")
data_re = re.ompile("Blah=(?P<value>\d)")
with open(f_name) as f:
need_search = False
for l in f:
if reg.search(l) is not None:
need_search = True
if need_search == True:
res = data_re.search(l)
if res is not None:
print res.groups('value')

Conditional elif statement is not yielding the correct results

The elif stament should print the log files and path that were not found in a search that I conduct. However, they yield every line that is searched in a single file (a plethora of info). What am I doing wrong?
for line in fileinput.input(walk_dir(directory, (".log", ".txt"))):
result = regex.search(whitespace.sub('', line))
if result:
template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n"
output = template.format(fileinput.filelineno(), fileinput.filename(), result.group())
print output
temp.write(output)
break
elif not result:
template = "\nLine: {0}\nString not found in File: {1}\nString Type: {2}\n\n"
output = template.format(fileinput.filelineno(), fileinput.filename(), result.group())
print output
temp.write(output)
else:
print "There are no files in the directory!!!"
Actual Code:
elif searchType =='2':
print "\nDirectory to be searched: " + directory
print "\nFile result2.log will be created in: c:\Temp_log_files."
paths = "c:\\Temp_log_files\\result2.log"
temp = file(paths, "w")
userstring = raw_input("Enter a string name to search: ")
userStrHEX = userstring.encode('hex')
userStrASCII = ''.join(str(ord(char)) for char in userstring)
regex = re.compile(r"(%s|%s|%s)" % ( re.escape( userstring ), re.escape( userStrHEX ), re.escape( userStrASCII )))
goby = raw_input("Press Enter to begin search (search ignores whitespace)!\n")
def walk_dir(directory, extensions=""):
for path, dirs, files in os.walk(directory):
for name in files:
if name.endswith(extensions):
yield os.path.join(path, name)
whitespace = re.compile(r'\s+')
for line in fileinput.input(walk_dir(directory, (".log", ".txt"))):
result = regex.search(whitespace.sub('', line))
if result:
template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n"
output = template.format(fileinput.filelineno(), fileinput.filename(), result.group())
print output
temp.write(output)
#break
elif result not in line:
output = fileinput.filename()
print output
temp.write(output)
break
else:
print "There are no files in the directory!!!"
You're iterating over every line of every file passed to fileinput.input(...), right? And you perform the if statement for every line. If the condition is true, then you break, but if the condition is false, you don't break, but write to temp. So for every line in fileinput.input that doesn't match the condition, you write a line to temp and print output. (Actually, the above is wrong -- see edit below.)
Also, elif str(result) not in line: will have strange results -- just use else as others have suggested. If result evaluates to false in this situation, then result == None, which means that str(result) == 'None', which means that if a line contains None, then you'll have unexpected results.
Edit: Ok, actually, looking more closely at your actual code the above is wrong, strictly speaking. But the point remains -- fileinput.input() returns a FileInput object that in essence concatenates the files and iterates over every line in turn. Since in some cases you don't want to perform an action per line, but per file, you'll have to iterate over them individually. You could do this without fileinput but since that's what you're using, we'll stick with that:
for filename in walk_dir(directory, (".log", ".txt")):
for line in fileinput.input(filename):
result = regex.search(whitespace.sub('', line))
if result:
template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n"
output = template.format(fileinput.filelineno(), fileinput.filename(), result.group())
print output
break # (assuming you only want to print the first result)
else:
ouput = fileinput.filename()
print output
temp.write(output)
break
The way this works: for every file in the list, this prints the first match in the file, or prints the filename if no match was found. You can use else with a for loop in python; the else block at the end of the loop is executed if the loop is not broken. Since no match was found, the filename is printed.
If you wanted to print out all matches in a file, you could save the matches in a list, and instead of using else, you could test the list. Simplified example:
matches = []
for line in fileinput.input(filename):
if searchline(line):
matches.append(line)
if matches:
print template.format(matches)
else:
print fileinput.filename()

Categories