Writing data in a CSV file everytime a function is called - python-3.x

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'

Related

Cryptography Decryption Problems

My script is a password manager which uses SQLITE3. I am having problems decrypting the data which I have recieved from my database.
The error:
cryptography.exceptions.InvalidSignature: Signature did not match digest,
raise InvalidToken,
cryptography.fernet.InvalidToken
comes up when I try to decode the data. My code is down below and I need help understanding and fixing the problem with decoding. (just focus on the find_password() function, load_key() function, and decode_data() functions)
#The Dependicies and Packages required for this script
import sqlite3
from cryptography.fernet import Fernet
def generate_key():
"""
Generates a key and save it into a file
"""
key = Fernet.generate_key()
with open("secret.key", "wb") as key_file:
key_file.write(key)
def load_key():
"""
Loads the key named `secret.key` from the current directory.
"""
return open("secret.key", "rb").read()
#These are the keys for encryption
key = load_key()
f = Fernet(key)
def decode_data(datas):
new_name = f.decrypt(datas)
final_name = new_name.decode()
return final_name
def create_password():
"""
This function is used for gathering the user's data about the website, their username to that site, and their password.
This data in then encrypted using the key generated at lines 5 and 6.
Finally, the data is pushed to the sql database using bind parameters so that there is no risk of sql injection attacks
"""
#Each of these variables asks for a input which is then encoded into bytes so that it can be encrypted.
#The user input is then encrypted using the keys generated on lines 5,6
encrypted_website = f.encrypt(input("What is the website that you have made a password for?>").encode())
encrypted_username = f.encrypt(input("What is the username for the website you are making a password for?>").encode())
encrypted_password = f.encrypt(input("What is the password for the website you are making?>").encode())
#This is the command which uses bind parameters to insert the encrypted data into the database. The type of data being inserted is a blob
c.execute("INSERT INTO passwords (website, username, password) VALUES (?, ?, ?)",
(encrypted_website, encrypted_username, encrypted_password))
def find_password():
"""
This function is to get the password of the website that the user expected
"""
website_name = input("What is the website's name for which you need a password>")
c.execute("SELECT * FROM passwords")
data = c.fetchall()
for row in data:
print(row[0])
name = decode_data(row[0])
if name == website_name:
password = decode_data(row[2])
print(f'The password to {website_name} is {password}')
def main():
go_on = True
while go_on:
direction_question = input("This is your password manager. Press 1 to create a new pasword, Press 2 to search for a password, or Press 3 to exit the program>")
if direction_question.lower() == "1":
create_password()
if direction_question.lower() == "2":
find_password()
if direction_question.lower() == "3":
go_on = False
else:
print("Invalid response")
db.commit()
db.close()
if __name__ == "__main__":
db = sqlite3.connect('password.db')
c = db.cursor()
# generate_key()
#This is the code to create the table
# c.execute("""CREATE TABLE passwords (
# website blob,
# username blob,
# password blob
# )""")
main()

How do I make my python program to write a new file

I am writing a program by which I can extract data from a file, and then based on some condition, I have to write that data to other files. These files do not exist and only the code will create these new files. I have tried every possible combination of print parameters but nothing is helping. The program seems to run fine with no error in IDLE but no new files are created. Can somebody give me a solution?
Here is my code:
try:
data= open('sketch.txt')
for x in data:
try:
(person, sentence)= x.split(':',1)"""data is in form of sentences with: symbol present"""
man=[] # list to store person
other=[] #list to store sentence
if person=="Man":
man.append(sentence)
elif person=="Other Man":
other.append(sentence)
except ValueError:
pass
data.close()
except IOError:
print("file not found")
try:
man_file=open("man_file.txt","w")""" otherman_file and man_file are for storing data"""
otherman_file=open("otherman_file.txt", "w")
print(man,file= man_file.txt)
print(other, file=otherman_file.txt)
man_file.close()
otherman_file.close()
except IOError:
print ("file error")
2 problems
you should use
man_file = open("man_file.txt", "w+")
otherman_file = open("otherman_file.txt", "w+")
w+ - create file if it doesn't exist and open it in write mode
Modes 'r+', 'w+' and 'a+' open the file for updating (reading and writing); note that 'w+' truncates the file..
https://docs.python.org/2/library/functions.html
2.
print(man,file= man_file.txt)
print(other, file=otherman_file.txt)
if sketch.txt file do not exist then "man" and "other" will not initialized
and in the print method will throw another exception
try to run this script
def func():
man = [] # list to store person
other = [] # list to store sentence
try:
data = open('sketch.txt', 'r')
for x in data:
try:
(person, sentence) = x.split(':', 1)
if person == "Man":
man.append(sentence)
elif person == "Other Man":
other.append(sentence)
except ValueError:
pass
data.close()
except IOError:
print("file not found")
try:
man_file = open("man_file.txt", "w+")
otherman_file = open("otherman_file.txt", "w+")
# print(man, man_file.txt)
# print(other, otherman_file.txt)
man_file.close()
otherman_file.close()
except IOError:
print ("file error")
func()

Using two kv files in one program error

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)

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.

Creating a function to ask user for a file

I'm trying to make function which asks the user for a filename. If the file is not found, it will keep asking. This what I have please help..
def return_text_file(infile):
while infile:
try:
file = open(infile)
except IOError:
print("Could not find the file specified")
infile = input ("Enter the file name")
return open_infile
file_input = input ("Enter the file name")
return_text_file(file_input)
You can create a function (e.g. ask_file_name below) to get a valid answer from the user. It will repeat constantly until an existing name is given.
import os
path_str = '/home/userblabla/ProjectBlabla/'
def ask_file_name():
files_detected = os.listdir(path_str)
while True:
print('\nFiles:')
for file in files_detected:
print(file)
file_name_given = input('\nFile name?')
if file_name_given not in files_detected:
print("Could not find the file specified")
else:
print('Thanks friend.')
return file_name_given
my_file_name = ask_file_name()
with open(my_file_name, 'r') as opened_file:
# Do stuff on opened_file
......
with open() automatically closes the file, and it might be better if you use it instead of open().

Resources