Return value as bool from text file - python

Trying to write multi scripts that would access one text file to retrieve their toggle values from the said text file and then return with a value as false and change it to true and vice versa.
Value always comes back as false, not sure what I'm missing but here is the text file:
1
False
3
True
5
6
7
8
9
Here is the source code:
def append():
with open('values', 'r') as file:
# read a list of lines into data
data = file.readlines()
# now change the line
re_value = value
data[1] = re_value+"\n"
# and write everything back
with open('values', 'w') as file:
file.writelines(data)
print("value changed to "+re_value)
def read() -> bool:
#opens the value file to find the value of the toggle
f=open("values", "r")
for x, line in enumerate(f):
if x == 1:
toggle = line
print(toggle)
return toggle
f.close()
toggle = read()
if toggle:
print("Light is on turn it off")
#runs command to turn off the light
#runs command to change value for light
value = "False"
append()
else:
print("Light is off turn it on")
#runs command to turn on the light
#runs command to change value for light
value = "True"
append()

Seems like the boolean value you are using to evaluate the condition is a string.
In this case you could keep it as string:
if value == "True":
print "Condition is true!"
Or implement something similar:
def str2bool(v):
return v.lower() in ("true",) # you can add to the tuple other values that you consider as true if useful
print str2bool(value)

Try this to toggle:
putback=[]
with open('values', 'r') as file:
for e in file.readlines():
if e=='True' or e=='False':
print(e)
putback.append(not e)
else:
putback.append(e)
with open('values','w') as file1:
file.write('\n'.join(putback))

Found my mistake guys, thank you for the help, changed the if statement to
if toggle=="True\n":
print("Light is on turn it off")
#runs command to turn off the light
#runs command to change value for light
value = "False"
append()
it was missing the new line tag as it is a multiline text document

From what i can understand you want to change True as False and False as True and leave the rest as it is.
final_output = []
with open("values") as file:
data = file.readlines()
for line in data:
line = eval(line.strip())
if isinstance(line, bool):
print("Value is {0} Changing to {1}".format(line, not line))
final_output.append(not line)
else:
final_output.append(line)
with open("values", 'w') as file:
file.write("\n".join([str(line) for line in final_output]))

Related

How to check if the first line has changed in a text file using python

I'm trying to write a script that will check if the first line of a text file has changed and print the value once. It needs to be an infinite loop so It will always keep checking for a change. The problem I'm having is when the value is changed it will keep constantly printing and it does not detect the new change.
What I need to is the script to constantly check the first line and print the value once if it changes and do nothing if it does not change.
This is what I tried so far:
def getvar():
with open('readme.txt') as f:
first_line = f.readline().strip('\n')
result = first_line
return result
def checkvar():
initial = getvar()
print("Initial var: {}".format(initial))
while True:
current = getvar()
if initial == current:
pass
else:
print("var has changed!")
pass
checkvar()
If the initial line has changed, set initial to current.
In the function checkvar()
def checkvar():
initial = getvar()
print("Initial var: {}".format(initial))
while True:
current = getvar()
if initial == current:
pass
else:
initial = current #initial line set to current line
print("var has changed!")
pass
You are never re-assigning initial, so when you check if initial == current, it's only checking against the very first version of the file. Instead, re-assign as follows
def getvar():
with open('readme.txt') as f:
first_line = f.readline().strip('\n')
result = first_line
return result
def checkvar():
last = getvar()
while True:
current = getvar()
if last != current:
print("var has changed!")
last = current
checkvar()

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

input in a function and remove lines from a file

I'm trying to make a modules and for one of the commands I need it to remove a specified user. I need help with it finding the line the user is at. Then deleting the username. Here is the code.
def delete_usr(usr):
file = open("Username.txt","r+")
count = 0
userfound = False
try:
for user in file.readlines():
count += 1
if usr == user.strip():
userfound = True
BTW i also need it to delete the password. The password has the same line as the username and is kept in password.txt
The closest solution to your suggestion would be:
def delete_usr(usr):
file = open("Username.txt","r+")
count = 0
userfound = False
for user in file.readlines():
#print(user.strip())
count += 1
if usr == user.strip():
userfound = True
#print("yeah")
#break
file.close()
If you use a try statement, you expect a perticular kind of error (eg. key not in a dictionary) and also should write except statement to catch the error.
If you use open(file), it is a good practice to also use file.close(). If you use the with statement, as in the example above, you don't need to do it as it is done automatically.
This should do the trick (as long as the user is only on a single line, else remove the break statement):
def delete_usr(usr):
with open("Username.txt","r") as myfile:
lines = myfile.readlines()
for idx, l in enumerate(lines):
if usr==l.split(':')[0]:
lines[idx] = ''
break
with open("Username.txt","w") as myfile:
[myfile.write(i) for i in lines]

Unbound Local Error in Python for File-reading

I have a function that reads in a data file and returns the values in that file as a list printing comments.
def loadcsv(filename):
"""Loads a comma-separated-value file (.csv) and returns a list of all the numerical values, ignoring comments and any malformatted data."""
"""Function should ignore bad data, but print all comments."""
datafile = open(filename)
global datafile
numbers = []
for line in datafile:
if line[0] == "#":
print line
elif line[0] != "#" or type(line[0]) != type(0) or type(line[0]) != type(0):
print "Bad Data"
else:
numbers.append(line)
datafile.close()
return numbers
Not sure how I get the error given my declaration of datafile as global.
The global statement needs to be the first line in your function, so just swap the global datafile and datafile = open(filename) lines.

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