I would like to count or add numbers to the file everytime I add something to it.
My file is consist of
Account|Username|Password
I would like to have it like this whenever the user adds another account.
# Account Username Password
1 Facebook Name Pass
My code of adding account is this
def add_account():
acc = input("Enter the name of your account.")
username = input(f"Enter the username of your {acc}")
password = input(f"Enter the password of your {acc}")
ask = input(f" Do you like to save {acc} credentials? Y|N")
if ask == "Y":
with open("myfile.txt", "a") as file:
file.write("" + "|" + acc + "|" + username + "|" + password)
file.close()
add_accout()
def view_account():
file = open("myfile.txt", "r")
line = file.readline()
for line in file:
a, b, c, d = line.split("|")
d = d.strip()
print(formatStr(a), formatStr(b), formatStr(c), formatStr(d))
view_account()
def formatStr(str):
nochars = 15
return str + (" "*(nochars - len(str))
How can I count the appended lines?
As jarmod is suggesting in the comments, you can use a global counting variable to number each added account:
counting = 0
def add_account():
global counting
acc = input("Enter the name of your account.")
username = input(f"Enter the username of your {acc}")
password = input(f"Enter the password of your {acc}")
ask = input(f" Do you like to save {acc} credentials? Y|N")
if ask == "Y":
counting += 1
with open("myfile.txt", "a") as file:
file.write("" + acc + username + password + str(counting))
file.close()
add_account()
If you need to be able to quit the program, restart it later, and have it discover the last account number stored in your database, then you can do this as follows to calculate the next free account number:
SEPARATOR = '|'
def next_account_number():
next_num = 1
with open("myfile.txt", "r") as f:
# Read lines discarding empty lines
lines = f.read().splitlines()
lines = list(filter(lambda x: x != "", lines))
if len(lines) > 1:
account = lines[-1].split(SEPARATOR)
try:
next_num = int(account[0]) + 1
except ValueError:
pass
return next_num
print("Next account number:", next_account_number())
Related
I have a code that generates characters. I want to make that my result from the for loop is saved in a file and all these results are separated using "/".
# -*- coding:utf -8 -*-
#!/usr/bin/python3
import random
chars = 'abcdefghijklnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
number = random.randint(4, 10)
length = random.randint(4, 18)
for n in range(number):
password = ''
for i in range(length):
password += random.choice(chars)
with open('randomfile.txt', 'w') as writer:
for line in password:
writer.write(" ".join(line) + "/")
Result:
3/p/A/N/8/K/v/n/f/t/Z/L/5/Y/s/J/7/E/
It turns out that it divides one password by "/", but I need to output the entire array and divide it. For example:
odcyUHFZ/n2s5gUvj/7SXRTy7D/Mw55R5kU/Afn7Pk7x/ZhHzqeWy/Vc5FSdck/a6oKWAiM
Try this:
password_list = ''
for n in range(number):
password = ''
for i in range(length):
password += random.choice(chars)
password_list += password + '/'
with open('randomfile.txt', 'w') as writer:
writer.write(password_list)
user = input("\nInput user's Login ID: ")
while True:
password = str(input ("Input user's Password: "))
rpass = str(input("Re-enter the Password: "))
if password == rpass:
file = open("username.txt", "a")
file.write (user)
file.close()
break
else:
print("You have entered the wrong password, Try Again")
I want make a program where users can sign up with their username and password and it can be stored into a txt file. And the next person that is going to sign up won't be able to use the same username.
I renewed the code but the same problem happened, the previous username is not detected.
Every time you write to the file, it appends to the same line.
if data == user+ ":" +password:
This condition is never true as a result.
One possible solution is to add \n after every write.
file.write (user +" : "+ password +"\n")
And your condition would be
if data == user+ " : " +password:
Be mindful of whitespaces and other characters. It should be an exact match with this method.
Edit: You're checking whether the new username and password together are a match.
What you should be doing is matching user with data.split(':')[0][:-1] -
if data.split(":")[0][:-1] == user
This will collect the string till the ':' and truncate the trailing space.
If you want to use the parse module, you can run pip install parse and use this code:
import parse
pattern = '{[a-z][A_Z][0-9]} : {[a-z][A_Z][0-9]}'
lines = []
user = input ("enter username: ")
password = input ("enter password: ")
with open('username.txt', 'r') as f:
line = f.readline()
while line:
u, p = parse.parse(pattern, line)
lines.append((u, p))
line = f.readline()
users = [ u for (u, p) in lines ]
if user in users:
print(f'Username {user} is taken, please try again.')
else:
with open('username.txt', 'a') as f:
f.write(f'{user} : {password}')
print(f'Username and password successfully created.')
I am trying to make a program to see if the username and password entered into a python program is the same as the username and password stored in a csv file.
logorsign = input("""Choose one:
1. Log in
2. Sign up
3. Quit
""")
print("")
if logorsign == "1":
Netflix_CSV = csv.reader(open("Netflix Task.csv", "rt"))
first_Line = next(Netflix_CSV)
checkuser = input("Enter Username: ")
print("")
checkpasw = input("Enter Password: ")
for row in Netflix_CSV:
if row[0] == checkuser:
print(watched_films)
This, above, is the code so far.
Please help,
Thanks in advance
The best data structure to use here is a dictionary:
user_passwords = dict()
user_films = dict()
user_logged_in = False
given_username = input('Enter Username: ')
print('')
given_password = input('Enter Password: ')
print('')
with open('Netflix Task.csv', 'r') as fh:
reader = csv.reader(fh)
reader.next() # Skip the header line
for line in reader:
username, password, watched_films = line
user_passwords[username] = password
user_films[username] = watched_films
if user_passwords.get(given_username, False) == given_password:
print('login successful')
user_logged_in = True
else:
print('Bad username/password')
Then, to access the user's films:
users_films = user_films[username]
def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
for line in lines:
username, lel, type = line.split("/")
while name == username:
name = input("input name again: ")
tip = True
with open("users.txt", "w") as users:
users.write(str(red))
#
#I do not know how to perform a given modification and enrollment into place in #the text.
#
#I wont to change word False to True for username i input.
#I have this text in file users:
#Marko123/male/False
#Mimi007/female/False
#John33/male/False
#Lisa12/female/False
#Inna23/female/False
#Alisa27/female/False
I won't to change word False to True for username I input.
I have this text in file users:
Marko123/male/False
Mimi007/female/False
John33/male/False
Lisa12/female/False
Inna23/female/False
Alisa27/female/False
You can just use the csv library and forget about string manipulation:
import csv
def false_to_true():
#read from user.txt file into list(data)
with open('users.txt', 'r') as userfile:
data = [row for row in csv.reader(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)]
while True:
#waiting for input until you enter nothing and hit return
username = input("input name: ")
if len(username) == 0:
break
#look for match in the data list
for row in data:
if username in row:
#change false to true
row[2] = True
#assuming each username is uniqe break out this for loop
break
#write all the changes back to user.txt
with open('users.txt', 'w', newline='\n') as userfile:
dataWriter = csv.writer(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)
for row in data:
dataWriter.writerow(row)
if __name__ == '__main__':
false_to_true()
Open the input and output files, make a set out of the user-input names (terminated by a blank line), then create a generator for strings of the proper format that check for membership in the user-input names, then write these lines to the output file:
with open('names.txt') as f, open('result.txt', 'w') as out:
names = {name for name in iter(input, '')}
f = ('{}/{}/{}'.format(a,b,'True\n' if a in names else c) for a,b,c in (line.split('/') for line in f))
output.writelines(f)
To modify a text file inplace, you could use fileinput module:
#!/usr/bin/env python3
import fileinput
username = input('Enter username: ').strip()
with fileinput.FileInput("users.txt", inplace=True, backup='.bak') as file:
for line in file:
if line.startswith(username + "/"):
line = line.replace("/False", "/True")
print(line, end='')
See How to search and replace text in a file using Python?
Ask for name and iterate throw your lines to check for username, like this:
def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
users = open("users.txt", "w")
for line in lines:
username, lel, type = line.split("/")
if name == username:
type = 'True\n'# \n for new line type ends with '\n'
users.write("/".join([username, lel, type]))
users.close()
false_to_true()
I'm currently working on a task where I must store scores in a text file. This is my code thus far:
def FileHandle():
score = str(Name) + ": " + str(correct)
File = open('Test.txt', 'a')
File.write(score)
File.close()
Name = input("Name: ")
correct = input("Number: ")
FileHandle()
My question is, how would I check already existed names in the text file and only add their score, rather than name and score, to the line it existed on?
This is what the file looks like:
Jonathon: 1
Micky: 5
How it would look after adding a score:
Jonathon: 1, 4
Mickey: 5
# The score added here is Jonathon's 4
Attempt:
# Accept scores
name = input("Name: ")
correct = input("Number: ")
if name in grade_book.keys and "," in grade_book.keys <= 2():
grade_book[name] += ',' + correct
else:
grade_book[name] = correct
If you are entering many scores at a time, I suggest reading the file into memory and working with things there. Doing an open/close on the file for every score update is very inefficient.
# Read the file into a dictionary
grade_book = {}
File = open('Test.txt', 'r')
for line in File:
name, scores = line.split(':')
grade_book[name] = scores.strip()
File.close()
print grade_book
# Accept scores
name = raw_input("Name: ")
while name != "":
correct = raw_input("Number: ")
if name in grade_book.keys():
grade_book[name] += ',' + correct
else:
grade_book[name] = correct
name = raw_input("Name: ")
# Write dictionary back to the file
File = open('Test.txt', 'w')
for name, scores in grade_book.items():
out_line = name + ':' + scores + "\n"
File.write(out_line)
File.close()
Unfortunately you would have to go over the file, find the correct line, edit it and write in a temp file and then move that file to original. Best first use a data structure like dict etc. to update scores and finally when done write or persist them.
def filehandle(name,correct):
temp = open('temp', 'wb')
with open('Test.txt', 'r') as f:
for line in f:
if line.startswith(name):
line = line.strip() + correct +'\n'
temp.write(line)
temp.close()
shutils.move('temp', 'data.txt')
You need to pass in the parameters while calling the functions.
Name = input("Name: ")
correct = input("Number: ")
filehandle(name, correct)