Storing data to a file within a programme - python

PYTHON
I am making a quiz and at the start I ask for the user to input a username. I want to be able to store the username and a high score that they get or the highest point. But i dont know how to store the username or to save every single one that has been submitted
Please help and be clear. Appreciated.
Thank you

You can use JSON to store the user information.
This is an example of what you may use.
import json
import os
DB_NAME = "db.json"
if not os.path.isfile(DB_NAME):
with open(DB_NAME, "w") as f:
json.dump({},f)
def get_db():
with open(DB_NAME) af f:
return json.load(f)
def write_db(db_dict):
with open(DB_NAME,'w') af f:
json.dump(f,indent=4)
if __name__ == "__main__":
username = raw_input("Username: ")
highscore = int(raw_input("High-score: "))
write_db(get_db()[username] = highscore)
This is the JSON documentation: link
To understand JSON better read this: link

Related

How can i delete a couple lines of text that I inputted into a text file in python?

I am making a small simple password manager in python. I have the functions of creating an account which has 3 inputs, Username, Password, and Website. I have a function to view all the accounts which shows the contents of the file info.txt where all that information goes. Im trying to create a function to delete an entry but im not sure how to make the function delete all the lines of information associated with the Username. I want an input asking "Which account to delete" you put the username, and it will delete all information associated with the username in info.txt
Code:
import os.path #Imports os module using path for file access
def checkExistence(): #Checking for existence of file
if os.path.exists("info.txt"):
pass #pass is used as a placeholder bc if no code is ran in an if statement and error comes.
else:
file = open("info.txt", "w") #creates file with name of info.txt and W for write access
file.close()
def appendNew():
#This function will append a new password in the txt file
file = open("info.txt", "a") #Open info.txt use a for appending IMPORTANT: opening a file with w for write will write over all existing data
userName = input("Enter username: ")
print(userName)
os.system('cls')
password = input("Enter password: ")
print(password)
os.system('cls')
website = input("Enter website: ")
print(website)
os.system('cls')
print()
print()
usrnm = "Username: " + userName + "\n" #Makes the variable usrnm have a value of "Username: {our username}" and a new line
pwd = "Password: " + password + "\n"
web = "Website: " + website + "\n"
file.write("----------------------------------\n")
file.write(usrnm)
file.write(pwd)
file.write(web)
file.write("----------------------------------\n")
file.write("\n")
file.close()
def readPasswords():
file = open("info.txt", "r") #Open info.txt with r for read
content = file.read() # Content is everything read from file variable (info.txt)
file.close()
print(content)
checkExistence()
while True:
choice = input("Do you want to: \n 1. Add account\n 2. View accounts\n 3. Delete account\n")
print(choice)
if choice == "1":
os.system('cls')
appendNew()
elif choice == "2":
os.system('cls')
readPasswords()
elif choice == "3":
os.system('cls')
else:
os.system('cls')
print("huh? thats not an input.. Try again.\n")
I tried making a delete account function by deleting the line which matched the username. My only problem is that it only deletes the line in info.txt with the username, but not the password and website associated with that username.
Firstly, you're using the wrong tool for the problem. A good library to try is pandas, using .csv files (which one can think of as pore program oriented excel files). However, if you really want to use the text file based approach, your solution would look something like this:
with open(textfile, 'r+') as f:
lines = [line.replace('\n', '') for line in f.readlines()]
# The above makes a list of all lines in the file without \n char
index = lines.index(username)
# Find index of username in these lines
for i in range(5):
lines.pop(index)
# Delete the next five lines - check your 'appendNew' function
# you're using five lines to write each user's data
print(lines)
f.write("\n".join(lines))
# Finally, write the lines back with the '\n' char we removed in line 2
# Here is your readymade function:
def removeName(username):
with open("info.txt", 'r+') as f:
lines = [line.replace('\n', '') for line in f.readlines()]
try:
index = lines.index(username)
except ValueError:
print("Username not in file!")
return
for i in range(5):
lines.pop(index)
print(lines)
f.write("\n".join(lines))
# Function that also asks for username by itself
def removeName_2():
username = input("Enter username to remove:\t")
with open("info.txt", 'r+') as f:
lines = [line.replace('\n', '') for line in f.readlines()]
try:
index = lines.index(username)
except ValueError:
print("Username not in file!")
return
for i in range(5):
lines.pop(index)
print(lines)
f.write("\n".join(lines))
# Usage:
removeName(some_username_variable)
removeName_2()
Again, this is a rather clunky and error prone approach. If you ever change the format in which each user's details are stored, your would have to change the number of lines deleted in the for loop. Try pandas and csv files, they save a lot of time.
If you're uncomfortable with those or you're just starting to code, try the json library and .json files - at a high level they're simple ways of storing data into files and they can be parsed with the json library in a single line of code. You should be able to find plenty of advice online about pandas and json.
If you're unable to follow what the function does, try reading up on try-except blocks and function parameters (as well as maybe global variables).

Save variable in pc python

I want to save a variable (user input fo mail) in pc. Because I don't want it to ask to login again and again. So please help me with how to store email variable in pc and also how to access it. Thank you.
I'm not sure what you want exactly.
If you just wanna save a text(I mean, string) in variable, then write it to a file like this.
f = open("some_file_to_save.txt", 'w')
f.write(your_variable)
f.close()
Or if you want data to be loaded as python variable again, then you can utilize pickle
May be you need config to your program?
So for this use the configparser
import configparser
You need 2 functions, first to Save:
def save_config(email):
config = configparser.ConfigParser()
config['DEFAULT'] = {
'Email': email
}
with open('config.ini', 'w') as configfile:
config.write(configfile)
And second to read saved data:
def read_config():
config = configparser.ConfigParser()
config.read('config.ini')
return config['DEFAULT']['Email']
Then add it to your code or use this example:
try:
email = read_config()
except:
print("Config doest contain email, type it:")
email = input()
print(f"My email is {email}")
save_config(email)

Storing data in .txt file and retrieving it

I was trying to make some sort of login system,
I have it so that if a username and password are in test.txt (there is multiple ones) it should let you login, I haven't even passed the step of verifying if the username and password are in the txt file and its destroying me, I don't know how to do it and I tried for hours, I made it so "if you find this username in the text file, give me the line number and check if the password this password is in the same line of the username ,(I used split (',')) , if both email and password entered are existent in the txt file and in the same line then..(didn't do that yet).
so it is confusing me, lots of errors, if no errors then it isn't working like I intended, here is my spaghetti code
def test():
with open('test.txt', 'r') as f:
for num, line in enumerate(f,1):
username = line.split(',')
if username in num:
if username == q1:
print("found user in line: " + num)
Line = num
password = line.split(',')
if password in Line:
if password == q2:
print("found pass in line: " + num)
can someone help me fix this and explain to me how storing data in .txt files work and how to retrieve them? YouTube and google didn't help much really, if you can suggest a video that will be cool too, because I'm confused at this point, all I have left is to try MongoDB because it has functions to retrieve data and store it already built in
but as its local on my pc not on the internet, I don't think I will need MongoDB, so that will be an overkill for a local test
With json, you can get it done this way:
JSON File
{
"user1":{"password":"123456"},
"user2":{"password": "abcde"}
}
Python
import json
def test(username, password):
with open("answer.json", "r") as read_it:
data = json.load(read_it)
if data[username][password] == '123456':
print('User found!')
else:
print('User or password doesn\'t exist')
test('user1', 'password')
If you want to use a text file, then as a simple example:
cat test.txt
aklaver, dog
adrian, cat
alklaver, fish
user_name = 'aklaver'
with open('test.txt', 'r') as pwd_file:
lines = pwd_file.readlines()
for line in lines:
user, pwd = line.split(',')
if user == user_name:
print(pwd)
dog

How to check for a string in csv files for verifying users in python

I have been trying to work out how to look for matching words in a csv file, such a user account detail.
What I have already done is creating two csv files with a username in one and a password in the other, putting them into python and then create a script that lets the user log in, but I can't get it to search for just one username if there are more than one in the csv file.
Here is my code:
import csv
#imports and loads usernames and passwords
usernames = []
passwords = []
infile = open("usernames.csv",'r')
reader=csv.reader(infile)
for i in reader:
usernames.append(i)
infile.close()
infile = open("passwords.csv",'r')
reader=csv.reader(infile)
for i in reader:
passwords.append(i)
infile.close()
#the log in script
def login():
print("Please enter your username:")
userlogin=input()
print("Please enter your password:")
passlogin=input()
if userlogin in usernames and passlogin in passwords:
print("Welcome, " + userlogin)
else:
print("Sorry, that's not a valid login")
Thank you for any help given
I think there is a flaw in your approach.
You cannot combine any username with any password.
If you are going to use your code this way,
One password will become applicable for all.
Try to create a dictionary or some kind of mapping where a single password will be checked instead of all present passwords.
If you want to add them, I would suggest using a pandas dataframe which will give you structure and checking will be easier as well.
import pandas as pd
df = pd.DataFrame()
df['usernames'] = pd.read_csv('usernames.csv')
df['passwords'] = pd.read_csv('passwords.csv')
if df[(df['usernames'] == your_user_name) &
(df['passwords'] == your_password)].empty() is not True:
print("username and password present")
else:
print("username and password not present")

CSV overwrites username and password in Python

I've been coding for a project and is to make a login/ sign in with python and by using csv file. The problem is that when it makes a user and password in the csv file it overwrites the previous one meaning their can only be one user and password.
My code right now looks like this...
import time
def sign_menu():
time.sleep(2)
print()
print(' Create a username and')
print( ' password')
NewUser = input(' Username: ')
NewpWord = input(' Password: ')
with open('UserPassword.csv', 'w') as outfile:
outfile.write("username," + NewUser)
outfile.write("password," + NewpWord)
Also my csv file looks like this...
username,password,
if you could improve the code it would be appreciated and if you could explain on how to make it not overwrite that would also be helpful.
Thank you.
The problem is that you use in your code the following line with 'w', which means (over)writing in the file:
open('UserPassword.csv', 'w')
Instead you should use 'a', which means appending to the file, as follows:
open('UserPassword.csv', 'a')

Categories

Resources