Using two kv files in one program error - python-3.x

I am quite new to OOP, and I am currently trying to create my first project using kivy. The program is currently stuck at the point of when I login I try and open a new kv file, but it will not open. Here is the python code:
window_widget = Builder.load_file("LiveScoringV104KVLoggedIn.kv")
class LoginScreen(Screen):
def checkLogin(self, username, password):
usernamesFile = open("dataUsernamesV104.txt", "r")
passwordsFile = open("dataPasswordsV104.txt", "r")
for line in usernamesFile.readlines():
for lineb in passwordsFile.readlines():
with open("dataprintedUsernameV104.txt", "w") as printedUsername:
printedUsername.write(username + "\n")
if line == username and lineb == password:
print("This is working")
return window_widget
else:
print("All wrong")
root_widget = Builder.load_file("LiveScoringV104KV.kv")
class StartupHome(App):
def build(self):
return root_widget
if __name__ == "__main__":
StartupHome().run()
when I login, which is correct because this is working is printed, window_widget is not called as it does not run the kv file, yet root_widget is called .How can I get the kv file to run like root_widget? (If you need the kv code just ask)

Related

Writing data in a CSV file everytime a function is called

I'm building an employee management system in which I've to write employees' data onto a file everytime the register system is called.
Below I wrote it onto a text file. And it's working fine.
class Employee:
def __init__(self, name, ID, password=None):
self.name = name
self.ID = ID
self.password = password
def register(self):
self.password = input("Enter your password: ")
database = open("Employees_data.txt", "a")
database.write("\n"+self.name+","+self.ID+","+self.password)
database.close()
return "Registration successfully!"
But I've to write data on a CSV file instead. I tried the following code but everytime I call the function, the previous line of data is overwritten.
def register(self):
self.password = input("Enter your password: ")
lst = [self.name, self.ID, self.password]
with open("Database.csv", "w", newline="") as data_file:
csv_writer = csv.writer(data_file, delimiter=",")
csv_writer.writerow(lst)
data_file.close()
return "Registration successfully!"
What do I do about it?
At first just delete this line. You don't need it.
data_file.close()
When you are using context manager in python it closes the file when writing in the file is finished.
after that, if you want to append your result to the file just instead of 'w' use 'a'

Why does Heroku not save changes that my code writes to a file?

If I run my code on my machine, the changes I write to the file using my code when it's incrementing the number inside count.txt by one are successfully written to count.txt. But, when my app is running on heroku, the changes to the file are neither made or saved. I opened terminal, did bash, cat count.txt, and read the contents of count.txt while users in my server were using the bot: there were no changes to the file. The number I manually put into the file is still there, unaltered. Is there a reason why this happens, and is there a solution?
import discord
from discord.ext import commands
import re
class Counting(commands.Cog):
""" Users take turns incrementing a number. """
def __init__(self, client):
self.client = client
self.count_channel = 761981805862846525
self.num_regex = re.compile(r'(^\d+)')
self.cum_num = None
self.filename = "count.txt"
#commands.Cog.listener()
async def on_message(self, message):
with open(self.filename) as f:
read_data = f.read()
self.cum_num = int(read_data)
if message.channel.id == self.count_channel:
try:
match_obj = self.num_regex.search(message.content)
if int(match_obj.group(1)) != self.cum_num + 1:
await message.author.send(f'Your message must start with **{self.cum_num + 1}**!')
await message.delete()
else:
self.cum_num += 1
with open(self.filename, 'w') as f:
f.write(str(self.cum_num))
except AttributeError:
if message.author.id != self.client.user.id:
await message.delete()
await message.author.send(f"Your message must be a number!")```
Heroku does not support such things. Use an online database instead. (I am using MongoDB for example).
Good luck!

Can't call a variable from another file

I have two files. The first file, we'll call it "a.py". The second, "b.py".
Here's an example of "a.py":
#!/usr/bin/env python
# coding=utf-8
CHOOSE = input ('''
\033[1;35m choose 1 or 2:\033[0m
1)tom
2)jack
''')
a = 666
b = "bbb"
def f():
print("this is a test")
return "function"
if __name__ == '__main__':
if CHOOSE == '1':
username = 'tom'
print(username)
elif CHOOSE == '2':
username = 'jack'
print(username)
else:
print('wrong choice,scipt is exit...')
Here's an example of "b.py":
#!/usr/bin/env python
# coding=utf-8
import a
from a import b,f,CHOOSE,username
a = a.a
f()
print(b,a,CHOOSE,username)
when i run python b.py,system feedback error:
wherem am i wrong?how to fix it?
Because this snippet:
if __name__ == '__main__':
if CHOOSE == '1':
username = 'tom'
print(username)
elif CHOOSE == '2':
username = 'jack'
print(username)
else:
print('wrong choice,scipt is exit...')
Will get executed only if the a.py run as the main python file not imported from other module, so username will not be defined so you can not import it. Here how to fix it:
a.py:
...
def foo(CHOOSE):
if CHOOSE == '1':
username = 'tom'
elif CHOOSE == '2':
username = 'jack'
else:
username = None
return username
b.py:
from a import foo
CHOOSE = input ('''
\033[1;35m choose 1 or 2:\033[0m
1)tom
2)jack
''')
username = foo(CHOOSE)
if username:
print(username)
else:
print('Wrong choice')
Explanation: First you need to extract the code that calculate the name into something reusable. Function are meant for code reusability so I defined one which take one parameter and it return the corresponding value. This function is then used (imported then invoked) in b.py.
Usually if __name__ == '__main__': is placed in the module that you consider your entry-point, so if you want to use it maybe b.py is a better place.
The block if __name__ == '__main__' only triggers if the script is run with a.py being the main module (e.g. you ran it using the command python a.py). If anything else was used as the main module, and a was imported, then this condition is not met and the code inside of it does not run.
The variable username is created and added to a's namespace in the if __name__ == '__main__' block. When you do python b.py, the code inside this block does not execute, and as a result username never gets added to the namespace. So when you try to import it, immediately after loading the file a, you get an error saying that the 'username' doesn't exist - it was never created.

CRUD program to read,write and append the details in txt file

It's a school assignment, an event management system. It will write the data to a txt file and retrieve it. Its mostly a CRUD program but not sure why it is not running. It shows space as an error on VS CODE IDE.
It will Create a customer, ask for the seats that he want to book. He can also delete the seats as per ref number before 24 hours.
import random
print("Welcome to the Event System")
def menu():
print("Choose the number from menu")
print("1:Create Customer")
print("2:Reserve a seat")
print("3.Cancel the seat")
print("4.Exit the Event System")
option = input("put down the number")
return option
def executingmenuinputchoice(option):
if(option == 1):
createcust()
elif(option == 2):
reserveseat()
elif(option == 3):
cancelseat()
elif(option == 4):
exit()
else:
print('you have chose a wrong option')
menu()
def createcust():
print('Provide Customer details')
name = input('Full name? --> ')
pno = input('phone number? -> ')
email = input('Email Id? --> ')
try:
file = open("cust.txt", "r")
lines = file.read().splitlines()
last_lines = lines[-1]
content = last_lines.split()
refno = random.randint(10001, 99999)
file.close()
file = open("cust.txt", "a")
file.write("\n"+" "+name+" "+pno+" "+email+" "+refno)
file.close()
print(refno + 'is your reference number')
print('Added Customer to file')
except IOError:
print("File doesn't exist at location")
except TypeError:
print('input proper data')
return createcust()
def customerexist(refno):
try:
file = open("cust.txt", "r")
for line in file:
content = line.split()
if (refno == int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("File doesn't exist")
file.close()
return False,0
def reserveseat():
referencenumber=input("Enter the Reference Number-->")
refexist =referenceexist(referencenumber)
if(refexist==True):
seatsyouwantbook=input("Number of seats you want to book? ->")
date=datetime.datetime.now()
seats=seats+seatsyouwantbook
newline=""
try:
file=open("cust.txt","r")
lines=file.read().splitlines()
last_linesno=len(lines)
currentLine=1
for line in lines:
content=line.split
if(currentline!=last_linesno):
if(refno==int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("FIle never existed")
file.close()
return False,0
def cancelseat():
try:
file=open("cust.txt","r")
for line in file:
content=line.split()
if (refno==int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("File doesn't exist")
file.close()
return False,0
invalid syntax (<unknown>, line 41)
I want it to run properly so, I can submit it again.
I haven't checked your whole code, but at least got it running to the point that you could further rectify it:-
import random
print("Welcome to the Event System")
def customerexist(refno):
try:
file = open("cust.txt", "r")
for line in file:
content = line.split()
if (refno == int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("File doesn't exist")
file.close()
return False,0
def reserveseat():
referencenumber=input("Enter the Reference Number-->")
refexist =referenceexist(referencenumber)
if(refexist==True):
seatsyouwantbook=input("Number of seats you want to book? ->")
date=datetime.datetime.now()
seats=seats+seatsyouwantbook
newline=""
try:
file=open("cust.txt","r")
lines=file.read().splitlines()
last_linesno=len(lines)
currentLine=1
for line in lines:
content=line.split
if(currentline!=last_linesno):
if(refno==int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("FIle never existed")
file.close()
return False,0
def cancelseat():
try:
file = open("cust.txt","r")
for line in file:
content=line.split()
if (refno==int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("File doesn't exist")
file.close()
return False,0
def createcust():
print('Provide Customer details')
name = input('Full name? --> ')
pno = input('phone number? -> ')
email = input('Email Id? --> ')
try:
file = open("cust.txt", "r")
lines = file.read().splitlines()
last_lines = lines[-1]
content = last_lines.split()
refno = random.randint(10001, 99999)
file.close()
file = open("cust.txt", "a")
file.write("\n"+" "+name+" "+pno+" "+email+" "+refno)
file.close()
print(refno + 'is your reference number')
print('Added Customer to file')
except IOError:
print("File doesn't exist at location")
except TypeError:
print('input proper data')
return createcust()
def menu():
print("Choose the number from menu")
print("1:Create Customer")
print("2:Reserve a seat")
print("3.Cancel the seat")
print("4.Exit the Event System")
option = input("put down the number")
return option
def executingmenuinputchoice(option):
option = int(option)
if(option == 1):
createcust()
elif(option == 2):
reserveseat()
elif(option == 3):
cancelseat()
elif(option == 4):
exit()
else:
print('you have chose a wrong option')
menu()
executingmenuinputchoice(menu())
REASON FOR ERRORS:-
Your indentation was all over the place, python language
prioritizes indentation as it uses it to figure out a block span, so you should
keep a consistent indentation scheme throughout your code.
Python uses top down approach for ~interpreting the
program, i.e. It only keeps track of the stuff that it had already
encountered. In your code, the function executingmeninputchoice()
and menu() (the two primary functions used for UI) were stacked
above all other function, therefore when you tried to call other
function from these two function, they aren't called. As the program
doesn't know whether these functions exists or not (as it hasn't
encountered them yet)
A logical error existed in function
executingmenuinputchoice(option) as you were trying to take in
input a string and were comparing it with integer values, and
therefore every time the operation failed and the control got shifted
to the else block, therefore every time you got the same output
'you have chose a wrong option' regardless of whether the input was
legal or not
P.S.:- I haven't tested your full code, as this isn't a code for me service, other logical errors may also exist, so I would recommend you to find and fix those too.

Error writing text into a .txt file in python

I am making a program that will
1. Create a text file
2. Allow a password to be stored
3. Allow a password to be changed
4. Add an additional password
5. Delete a specific password
The problem is in def delete():. I put in three passwords on three seperate lines: first, second, third. When I choose to delete password "second", it reprints the list from before, and then prints the new list at the end of the last password.
Here is my code:
import time
def create():
file = open("password.txt", "w")
passwordOfChoice = input("The password you want to store is: ")
file.write(passwordOfChoice)
print ("Your password is: ", passwordOfChoice)
file.close()
time.sleep(2)
def view():
file = open("password.txt","r")
print ("Your password is: ",
"\n", file.read())
file.close()
time.sleep(2)
def change():
file = open("password.txt", "w")
newPassword = input("Please enter the updated password: ")
file.write(newPassword)
print ("Your new password is: ", newPassword)
file.close()
time.sleep(2)
def add():
file = open("password.txt", "a")
extraPassword = input("The password you want to add to storage is: ")
file.write("\n")
file.write(extraPassword)
print ("The password you just stored is: ", extraPassword)
file.close()
time.sleep(2)
def delete():
phrase = input("Enter a password you wish to remove: ")
f = open("password.txt", "r+")
lines = f.readlines()
for line in lines:
if line != phrase+"\n":
f.write(line)
f.close()
print("Are you trying to: ",
"\n1. Create a password?",
"\n2. View a password?",
"\n3. Change a previous password?",
"\n4. Add a password?",
"\n5. Delete a password?",
"\n6. Exit?\n")
function = input()
print("")
if (function == '1'):
create()
elif (function == '2'):
view()
elif (function == '3'):
change()
elif (function == '4'):
add()
elif (function == '5'):
delete()
elif (function == '6'):
print("Understood.", "\nProgram shutting down.")
time.sleep(1)
else:
print("Your answer was not valid.")
print("Program shutting down...")
time.sleep(1)
To show what I meant above, here is my output:
Your password is:
first
second
thirdfirst
third
Can someone please tell me how to fix my def delete(): function so that it will not rewrite the original data? Thanks a ton!
The problem lies with the 'r+' mode. When you use 'r+' you can read and write, sure, but it's up to you to control where in the file you write.
What's happening is you read the file, and the cursor is stuck at the end, so when you write it back, Python dutifully puts your new lines on the end of the file.
See the docs about file methods; you're looking for something like seek.

Resources