Recalling words from external files and using them as values - python

So i am trying to read words off of a .txt file to determine the order of functions in my script. It reads the line correctly but does not actually do what it is supposed to. any help would be much appreciated, as I am at a loss for where the problem even starts.
settings_file = open('Settings.txt', 'r')
homescreen_order_string_1 = ['assignments ']
homescreen_order_string_2 = ['checklists ']
homescreen_order_string_3 = ['custom text ']
lines = settings_file.readlines()
lines_to_read_1 = [3]
def readline(lines):
if lines in homescreen_order_string_1:
return "assignments"
elif lines in homescreen_order_string_2:
return "checklists"
elif lines in homescreen_order_string_3:
return "custom text"
else:
return "err"
with open('Settings.txt', 'r') as settings_file:
for position, lines in enumerate(settings_file):
if position in lines_to_read_1:
if readline(lines) == "assignments":
print("yay") #placeholder for function to display assignments
break
elif readline(lines) == "checklists":
print('yay 2') #placeholder for functions to display checklists
break
elif readline(lines) == "custom text":
print("yay3") #placeholder for function to display custom text
break
elif readline(lines) == "err":
print("err")
print(lines) #this is just for bug testing, to see what the system is actualy seeing.
break
else:
pass
#here is the .txt file I am trying to pull from:
#-----------------------------------------
#Settings:
# order of homescreen print:
#assignments
#checklists
#custom text
#
# Custom Text:
#you have no custom text!-

Consider doing this with a dictionary that maps your commands to a function:
settings_file = open('Settings.txt', 'r')
def assignment_handler():
print("yay")
def checklists_handler():
print("yay 2")
def custom_handler():
print("yay 3")
handlers = {
'assignments': assignment_handler,
'checklists': checklists_handler,
'custom text': custom_handler
}
with open('Settings.txt', 'r') as settings_file:
for position, line in enumerate(settings_file):
line = line.strip()
if position in lines_to_read_1:
if line in handlers:
handlers[line]()
else:
print( "Unknown choice", line )

Related

How can I write an array to a .txt file, and then fill an array with the same.txt file?

So I'm doing a ToDo app, and I need to save an array of sentences and words to a .txt file. I have done some research but haven't found any tutorials that explain it well enough so I could understand it. As I said I'm using Python 3. Code below:
# Command line TO-DO list
userInput = None
userInput2 = None
userInput3 = None
todo = []
programIsRunning = True
print("Welcome to the TODO list made by Alex Chadwick. Have in mind
that closing the program will result in your TODO"
" list to DISAPPEAR. We are working on correcting that.")
print("Available commands: add (will add item to your list); remove
(will remove item from your list); viewTODO (will"
" show you your TODO list); close (will close the app")
with open('TODOList.txt', 'r+') as f:
while programIsRunning == True:
print("Type in your command: ")
userInput = input("")
if userInput == "add":
print("Enter your item")
userInput2 = input("")
todo.append(userInput2)
continue
elif userInput == "viewTODO":
print(todo)
continue
elif userInput == "remove":
print(todo)
userInput3 = input("")
userInput3 = int(userInput3)
userInput3 -= 1
del todo[userInput3]
continue
elif userInput == "close":
print("Closing TODO list")
programIsRunning = False
continue
else:
print("That is not a valid command")
This sounds like a job for pickle!
Pickle is a built-in module for saving objects and data in Python. To use it, you will need to put import pickle at the top of your program.
To save to a file:
file_Name = "testfile.save" #can be whatever you want
# open the file for writing
fileObject = open(file_Name,'wb')
# this writes the object to the file
pickle.dump(THING_TO_SAVE,fileObject)
# here we close the fileObject
fileObject.close()
To load from a file:
# we open the file for reading
fileObject = open(file_Name,'r')
# load the object from the file
LOADED_THING= pickle.load(fileObject)
fileObject.close()
The code in this answer was taken from here.
I hope that helps!
You use a simple text file to store your TODO - items and retrieve them from it:
import sys
fn = "todo.txt"
def fileExists():
"""https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-fi
answer: https://stackoverflow.com/a/82852/7505395
"""
import os
return os.path.isfile(fn)
def saveFile(todos):
"""Saves your file to disk. One line per todo"""
with open(fn,"w") as f: # will overwrite existent file
for t in todos:
f.write(t)
f.write("\n")
def loadFile():
"""Loads file from disk. yields each line."""
if not fileExists():
raise StopIteration
with open(fn,"r") as f:
for t in f.readlines():
yield t.strip()
def printTodos(todos):
"""Prints todos with numbers before them (1-based)"""
for i,t in enumerate(todos):
print(i + 1, t)
def addTodo(todos):
"""Adds a todo to your list"""
todos.append(input("New todo:"))
return todos
def deleteTodos(todos):
"""Prints the todos, allows removal by todo-number (as printed)."""
printTodos(todos)
i = input("Which number to delete?")
if i.isdigit() and 0 < int(i) <= len(todos): # 1 based
r = todos.pop(int(i) - 1)
print("Deleted: ", r)
else:
print("Invalid input")
return todos
def quit():
i = input("Quitting without saving [Yes] ?").lower()
if i == "yes":
exit(0) # this exits the while True: from menu()
def menu():
"""Main loop for program. Prints menu and calls subroutines based on user input."""
# sets up all available commands and the functions they call, used
# for printing commands and deciding what to do
commands = {"quit": quit, "save" : saveFile, "load" : loadFile,
"print" : printTodos,
"add": addTodo, "delete" : deleteTodos}
# holds the loaded/added todos
todos = []
inp = ""
while True:
print("Commands:", ', '.join(commands))
inp = input().lower().strip()
if inp not in commands:
print("Invalid command.")
continue
# some commands need params or return smth, they are handled below
if inp == "load":
try:
todos = [x for x in commands[inp]() if x] # create list, no ""
except StopIteration:
# file does not exist...
todos = []
elif inp in [ "save","print"]:
if todos:
commands[inp](todos) # call function and pass todos to it
else:
print("No todos to",inp) # print noting to do message
elif inp in ["add", "delete"]:
todos = commands[inp](todos) # functions with return values get
# todos passed and result overwrites
# it
else: # quit and print are handled here
commands[inp]()
def main():
menu()
if __name__ == "__main__":
sys.exit(int(main() or 0))

How to search a string in JS file (multiple lines) 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")

Tricks between plain python script and functions?

As a very newbie to programming, I tried to test every function individually, make sure it works right.
Here is my problem: for single plainly test, it works; turn it to functions and combine them into a script, them don't work.
For example:
def getRigs (fileObj):
fileObj.seek(0)
rigList = []
Tag = False
for line in fileObj:
if line.find("[BeginRigs]") != -1:
Tag = True
elif line.find("[EndRigs]") != -1:
Tag = False
elif Tag:
rigList.append(line.strip())
return (rigList)
def getObjects (fileObj):
fileObj.seek(0)
objList = []
Tag = False
for line in fileObj:
if line.find("[BeginObjects]") != -1:
Tag = True
elif line.find("[EndObjects]") != -1:
Tag = False
elif Tag:
objList.append(line.strip())
return (objList)
def dummyRig (rigObj, objName):
dummy = ""
for rig in rigObj:
with open(rig, "r") as infile:
#rigObj.seek(0)
Tag = None
for line in infile:
for obj in objName:
if line.find("ObjectAlias " + obj + "\n") !=-1:
Tag = "Mark"
dummy += line
break
elif line.find("BeginKeyframe") != -1:
if Tag == "Mark":
Tag = "Copy"
break
elif line.find("EndKeyframe") != -1:
if Tag == "Copy":
Tag = None
dummy += line
break
if Tag == "Copy":
dummy += line
return (dummy)
def getBlock (rigObj, objName):
Tag = False
block = ""
for line in rigObj:
if line.find("ObjectAlias " + str(objName) + "\n") != -1:
for line in rigObj:
if line.find("BeginKeyframe") != -1:
Tag = True
elif line.lstrip().startswith("0.000 ") and line.rstrip().endswith("default"):
Tag = False
break
elif Tag:
block += line
return (block)
inputconfig = open("config.cfg", "r")
infile = sys.argv[1]
inputscene = open(infile, "r")
outfile = infile.split(".")[0] + "_updated.fxs"
outputscene = open(outfile, "w")
a_rigList = getRigs (inputconfig)
a_objList = getObjects (inputconfig)
a_dummyRig = dummyRig (a_rigList, a_objList)
#print a_dummyRig #----> Output as expected
tmp = getBlock (a_dummyRig, a_objList)
outputscene.write(tmp) #----> Gvie me empty output!
If I test "getBlock" function individually, it works fine:
with open("result_from_a_dummyRig", "r") as rigObj, open("result", "w") as output:
Tag = False
for line in rigObj:
if line.find("ObjectAlias " + "rooster_bn_featherLa_rt_08" + "\n") != -1:
for line in rigObj:
if line.find("BeginKeyframe") != -1:
Tag = True
elif line.lstrip().startswith("0.000 ") and line.rstrip().endswith("default"):
Tag = False
break
elif Tag:
output.write(line)
What am I doing wrong?
EDIT: Add more of my code, hope it helps for the question. The code is design for copy some external data from other files to update my current files.
Thanks bruno, I got your point. The dummyRig function give me a string but not a "real" file. And getBlock function needs a "real" file input. Right?
Still hope someone give me more useful helps, I am not a programmer, I don't know much about python.
In your "test", you are iterating over an opened file. The file iterator iterate over the file's lines.
In your script, what you're passing to getBlock is a string, so you're iterating over the string's individual characters. No surprise you don't get the same results.
If you want getBlock to be able to work on both an opened file OR some arbitray string, you have to wrap the string in some file-like object that will iterate over line, not chars. The stdlib's StringIO module comes to mind...
Also if you really want to be serious about tests, use some automated unittest framework (unittest might not be the most sexy but it's in the stdlib) and make sure you really test the same thing that you will pass to your function ;)

Appending to a file, then reading from it into a list, then re-appending to it and overwriting certain parts

I want to be able to have a program whereby the user can input a paragraph/sentence/word/character whatever and have that stored in a list e.g. in list[0]. Then I want them to be able to write another bit of text and have that stored in e.g. list[1]. Then at any time I want the user to be able to read that from the list by choosing which segment they want to read from e.g. reading "hello" from list[0] whilst in list[1] "hi" is stored. Then when the user exits the program I want the list to be written to an external file. Then, at next start up, the program should read the file contents and store it again in the list so that the user can add more bits of text or read the current bits. When the list is saved to a file it should append new or changed parts but overwrite parts that are the same so as not to have duplicates. I have attempted this without much success. I am to be honest not sure if it is possible. I have browsed similar forums and have found that hasn't helped much so here it is.
My code so far:
import os
import time
import csv
global write_list
global f1_contents
write_list = []
def write():
os.system("cls")
user_story = input("Enter your text: \n")
write_list.append(user_story)
def read():
os.system("cls")
user_select_needs = True
while user_select_needs == True:
user_select = input("Enter the list section to read from or type exit: \n")
if user_select == "exit":
user_select_needs = False
try:
int(user_select)
select = user_select
select = int(select)
try:
print(write_list[select])
user_select_needs = False
enter = input("Press enter:")
except:
print("There is not stored data on that section!")
except ValueError:
print("That is not a valid section!")
def exit():
os.system("cls")
max_num_needs = True
while max_num_needs == True:
set_max_num = input("Set the storage: \n")
try:
int(set_max_num)
max_num = set_max_num
max_num = int(max_num)
max_num_needs = False
except:
print("It must be an integer!")
for i in range(0, max_num):
f = open("Saves.txt", "a")
f.write(write_list[i])
f.close()
os._exit(1)
def main():
store_num_needs = True
while store_num_needs == True:
set_store_num = input("State the current storage amount: \n")
try:
int(set_store_num)
store_num = set_store_num
store_num = int(store_num)
store_num_needs = False
except:
print("It must be an integer!")
try:
f1 = open("Saves.txt", "r")
for i in range(0, store_num+1):
i, = f1.split("#")
f1.close()
except:
print("--------Loading-------")
time.sleep(1)
while True:
os.system("cls")
user_choice = ""
print("Main Menu" + "\n" + "---------")
print("1) Write")
print("2) Read")
print("3) Exit")
while user_choice not in ["1", "2", "3"]:
user_choice = input("Pick 1, 2 or 3 \n")
if user_choice == "1":
write()
elif user_choice == "2":
read()
else:
exit()
if __name__ == "__main__":
main()
It might be too complicated to understand in which case just ask me in comments- otherwise general tips would be nice aswell.
Thanks in advance
A quick point of correction:
global is only required if you're defining a global variable inside a non-global context. In other words, anything defined at the default indentation level, will be accessible by everything else defined below it. For example:
def set_global():
x = 1
def use_global():
x += 1
set_global()
try:
use_global()
except Exception as e:
# `use_global` doesn't know
# about what `set_global` did
print("ERROR: " + str(e))
# to resolve this we can set `x` to a
# default value in a global context:
x = 1
# or, if it were required, we
# could create a global variable
def make_global():
global x
make_global()
# either will work fine
set_global()
use_global()
print(x) # prints 2
Now to the actual question:
I haven't read through the block of code you wrote (probably best to trim it down to just the relevant bits in the future), but this should solve the problem as I understand it, and you described it.
import os
import sys
user_text = []
# login the user somehow
user_file = 'saves.txt'
def writelines(f, lines):
"""Write lines to file with new line characters"""
f.writelines('\n'.join(lines))
def readlines(f):
"""Get lines from file split on new line characters"""
text = f.read()
return text.split('\n') if text else []
class _Choice(object):
"""Class that is equivalent to a set of choices
Example:
>>> class YesObj(Choice):
>>> options = ('y', 'yes')
>>> Yes = YesObj()
>>> assert Yes == 'yes'
>>> assert Yes == 'y'
>>> # assertions evaluate to True
Override the `options` attribute to make use
"""
allowed = ()
def __eq__(self, other):
try:
s = str(other)
except:
raise TypeError("Cannot compare with non-string")
else:
return s.lower() in self.allowed
def _choice_repr(choices):
allowed = []
for c in choices:
if isinstance(c, _Choice):
allowed.extend(c.allowed)
else:
allowed.append(c)
if len(allowed) > 2:
s = ', '.join([repr(c) for c in allowed[:-1]])
s += ', or %s' % repr(allowed[-1])
elif len(allowed) == 1:
s = '%s or %s' % allowed
else:
s = '%s' % allowed[0]
return s
def _choice_sentinel(name, allowed):
"""Creates a sentinel for comparing options"""
return type(name, (_Choice,), {'allowed': list(allowed)})()
Quit = _choice_sentinel('Quit', ('q', 'quit'))
Yes = _choice_sentinel('Yes', ('y', 'yes'))
No = _choice_sentinel('No', ('n', 'no'))
def readline_generator(f):
"""Generate a file's lines one at a time"""
t = f.readline()
# while the line isn't empty
while bool(t):
yield t
t = f.readline()
def read_from_cache():
"""Overwrite `user_text` with file content"""
if not os.path.isfile(user_file):
open(user_file, 'w').close()
globals()['user_text'] = []
else:
with open(user_file, 'r') as f:
lines = readlines(f)
# replace vs extend user text
for i, t in enumerate(lines):
if i == len(user_text):
user_text.extend(lines[i:])
else:
user_text[i] = t
def write_to_cache():
"""Overwrite cache after the first line disagrees with current text
If modifications have been made near the end of the file, this will
be more efficient than a blindly overwriting the cache."""
with open(user_file, 'r+') as f:
i = -1
last_pos = f.tell()
# enumerate is a generator, not complete list
for i, t in enumerate(readline_generator(f)):
if user_text[i] != t:
# rewind to the line before
# this diff was encountered
f.seek(last_pos)
# set the index back one in
# order to catch the change
i -= 1
break
last_pos = f.tell()
# then cut off remainder of file
f.truncate()
# recall that i is the index of the diff
# replace the rest of it with new
# (and potentially old) content
writelines(f, user_text[i+1:])
def blind_write_to_cache():
"""Blindly overwrite the cache with current text"""
with open(user_file, 'w') as f:
writelines(f, user_text)
def overwrite_user_text(i, text, save=False):
"""Overwrite a line of text
If `save` is True, then these changes are cached
"""
try:
user_text[i] = text
except IndexError:
raise IndexError("No text exists on line %r" % (i+1))
if save:
write_to_cache()
def user_input():
"""Get a new line from the user"""
return raw_input("input text: ")
def user_choice(msg, choices):
if len(choices) == 0:
raise ValueError("No choices were given")
ans = raw_input(msg)
if ans not in choices:
print("Invalid Response: '%s'" % ans)
m = "Respond with %s: " % _choice_repr(choices)
return user_choice(m, choices)
else:
return ans
def user_appends():
"""User adds a new line"""
user_text.append(user_input())
def user_reads(*args, **kwargs):
"""Print a set of lines for the user
Selects text via `user_text[slice(*args)]`
Use 'print_init' in kwargs to choose how
many lines are printed out before user must
scroll by pressing enter, or quit with 'q'."""
print_init = kwargs.get('print_init', 4)
sliced = user_text[slice(*args)]
if not isinstance(sliced, list):
sliced = [sliced]
for i, l in enumerate(sliced):
if i < print_init:
print(l)
sys.stdout.flush()
elif user_choice(l, ['', Quit]) == Quit:
break
def user_changes(i=None, save=False):
"""User changes a preexisting line"""
attempt = True
while i is None and attempt:
# get the line the user wants to change
i_text = raw_input("Line to be changed: ")
try:
# make user input an index
i = int(i_text)
except:
# check if they want to try again
c = user_choice("Bad input - '%s' is not an "
"integer. Try again? " % i_text, (Yes, No))
attempt = (c == Yes)
if attempt:
# user gave a valid integer for indexing
try:
user_reads(i-1)
overwrite_user_text(i-1, user_input(), save)
except Exception as e:
print("ERROR: %s" % e)
if user_choice("Try again? ", (Yes, No)):
user_changes(i, save)
# stores whatever text is already on
# file to `user_text` before use
read_from_cache()

How to search for a string in text files?

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")

Categories