Storing multiple passwords - python-3.x

I need to be able to store multiple usernames in a separate text file and access each username individually.
My code currently writes them all on the same line
This is what i have got
start=input("Please enter either Login or Signup.")
if start=="Signup":
First_name=input("Please enter your first name")
Last_name=input("Please enter your last name")
age=input("Please enter your age")
Usernames=open("Username_file","r")
Username1=(Usernames.read())
Username=(First_name[0:3])+age
Usernames=open("Username_file","w")
Usernames.write(Username1)
Usernames.write(Username)
Usernames.close()
Usernames=open("Username_file","r")
for line in Usernames:
print (line)

You are going about it the wrong way:
If you just want to add their first and last names to the end of the file 'Username_file.txt', you are doing it too complicatedly. Currently, your reading in the entire file to a variable and then writing the contents of the file before (from that variable) and the inputted name back to the same file.
The docs state that a is an option for open() which allows you to append to the file. This means you can just write the new username on without having to open it twice writing the same thing.
To do this, your code could look something like:
start = input("Please enter either Login or Signup: ")
if start == "Signup":
First_name = input("Please enter your first name: ")
Last_name = input("Please enter your last name: ")
age = input("Please enter your age: ")
with open("Username_file.txt", "a") as f:
f.write(First_name[0:3]+age+"\n")
with open("Username_file.txt", "r") as f:
for line in f:
print(line)

Related

open() in append mode is not behaving as expected

i am trying to create a program that asks to the user what they want to do to a file read/append/delete the file.
FileName = open(input("Enter file name: "))
ReadFile = FileName.read()
Decision = input("Do you want to read/delete/append to the file?: ")
if Decision == "read":
print(ReadFile)
FileName.close()
elif Decision == "append":
Append = input("Type what you want to add: ")
with open("FileName","a") as file:
file.write(Append)
but when i check the file the it doesn't append it
This is happening because you're not actually opening the same file. You're asking the user for input to specify a file's location for reading that file, but should they choose to "append" the file, you have them append to a file that has nothing to do with the file they specified. You're having the user append a file called "FileName". You have hard coded that string as the file's location when the user chooses to "append".
Here, FileName is not a string representing the file's location. This is an object representing the file.
FileName = open(input("Enter file name: "))
You had the user enter a string to the file's path, but you didn't store that string value. You used that value to open() a file up for reading.
Here, you're opening a file called "FileName" in what is likely the directory python started in, since there's no path visible here.
with open("FileName","a") as file:
file.write(Append)
Go look in your starting directory and see if you've created a new file called "FileName".
Keep in mind, if you open a file with mode="a", and that file does not exist, a new file will be created.
https://docs.python.org/3/library/functions.html#open
I would also like to use this moment to inform you about PEP8, Python's styling guide. It's not law, but following it will help other Python programmers help you quicker.
With that said, consider making your code snippet look more like the following code:
filename = input("Enter file name: ")
decision = input("Do you want to read/delete/append to the file?: ")
if decision == "read":
with open(filename) as file:
print(file.read())
elif decision == "append":
append = input("Type what you want to add: ")
with open(filename, "a") as file:
file.write(append)

Can I use a variable's name instead of the value of that variable?

So I have a pretty basic program that prompts for user input, then uses regex to look through the lines of a file and replace selected text with the values the user input.
I do currently have this working, but it's pretty clunky, with 24 lines asking for user input (I believe this is unavoidable), and another 24 lines for the Regex Substitution.
What I'd like to do, if possible, is replace those 24 Regex Lines with a single line that selects text to replace based on the variable name.
I was thinking of using an array for the variables, then using a for loop to run through them.
This is the code I'm currently using. It works fine, it just seems like a brute force method.
hostname = input("Please enter the hostname of the device: ")
switch = input("Please enter the switch that the device connects to: ")
switch_ip = input("Please enter the ip address of that switch: ")
for line in fileinput.input(inplace=1, backup='.bak'):
line = re.sub('<hostname>',hostname, line.rstrip())
line = re.sub('<switch>',switch, line.rstrip())
line = re.sub('<switch-ip>',switch_ip, line.rstrip())
print(line)
I was thinking of something like this:
hostname = input("Please enter the hostname of the device: ")
switch = input("Please enter the switch that the device connects to: ")
switch_ip = input("Please enter the ip address of that switch: ")
var_array[] = hostname, switch, switch_ip
for line in fileinput.input(inplace=1, backup='.bak'):
for v in var_array[]:
line = re.sub('<v>',v, line.rstrip())
print(line)
The important thing though would be that the v in '' would need to have the variable name as the value, not the value of the variable itself, so the Regex works properly.
So, at var_array[0] the line
line = re.sub('<v>',v, line.rstrip())
becomes
line = re.sub('<hostname>',hostname, line.rstrip())
I feel like this is something that should be possible, but I can't find anything on how to do this.
Any and all help appreciated.
You can just create a dict of variable names as key and values as value.
var_map = {}
var_map['hostname'] = input("Please enter the hostname of the device: ")
var_map['switch'] = input("Please enter the switch that the device connects to: ")
var_map['switch_ip'] = input("Please enter the ip address of that switch: ")
for line in fileinput.input(inplace=1, backup='.bak'):
for var, val in var_map.items():
line = re.sub(f'<{var}>', val, line.rstrip())
print(line)

How can I print the required row when reading a csv file in python

I am a beginner of python, I have an assignment that wants me to read a csv file and print out the related information.
I have an excel file which includes student's ID, school and hobby.
now I want to write a program to show the detail of the student by entering the ID.
requirements are:
print the entire row when ID is correctly input
print "Empty, try again" when ID input is space
print "No record" when the input is invalid or there is no matching record
I manage to fulfill the first 2 requirements but have no idea how to get the third. Seems like my code is always looping through each of the data and print "No record" every time, i.e. if there are 3 records, 3 "No record" will be printed. Could someone help me with it? Much thanks! Below will be my code.
import csv
file = "a.csv"
sID = input("Enter ID: ")
while (sID == " "):
print("Empty input,enter again")
sID = input("Enter ID: ")
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if (sID == row["id"]):
print("{0}{1}{2}".format(row[id],row[school],row[hobby])
else:
print("No record")
You need a few changes:
You should use the str.strip() method to test if a string is empty so that it accounts for any number of spaces.
You should quote the column names to make them string literals when using them as indices to access the value of a column in the current row.
You should use the optional else block for your for loop to determine that there is no matching record found, and break the loop if there is one found.
You are missing a right parenthesis for the print call that outputs a row.
With the above changes, your code should look like:
import csv
file = "a.csv"
sID = input("Enter ID: ")
while not sID.strip():
print("Empty input,enter again")
sID = input("Enter ID: ")
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if (sID == row["id"]):
print("{0}{1}{2}".format(row['id'],row['school'],row['hobby']))
break
else:
print("No record")

newbie python - adding 'cilent' into the txt file

I'm working on a registration in my school project, and one part of it is about registartion. I have to input client in form of
username
password
name
lastname
role
so he can be registered and appended into the txt file,
but i also have to make "username" be the unique in file (because I will have the other cilents too) and "password" to be longer than 6 characters and to possess at least one number.
Btw role means that he is a buyer. The bolded part I didn't do and I need a help if possible. thanks
def reg()
f = open("svi.txt","a")
username = input("Username: ")
password = input("Password: ")
name = input("Name of a client: ")
lastname = input("Lastname of a client: ")
print()
print("Successful registration! ")
print()
cilent = username + "|" + password + "|" + name + "|" + lastname + "|" + "buyer"
print(cilent,file = f)
f.close()
You need to add some file parsing and logic in order to accomplish this. Your jobs are to:
1: Search the existing file to see if the username exists already. With the formatting as you've given it, you need to search each line up to the first '|' and see if the new user is uniquely named:
name_is_unique = True
for line in f:
line_pieces = line.split("|")
test_username = line_pieces[0]
if test_username == username:
name_is_unique = False
print("Username already exists")
break
2: See if password meets criteria:
numbers=["0","1","2","3","4","5","6","7","8","9"]
password_contains_number = any(x in password for x in numbers)
password_is_long_enough = len(password) > 6
3: Write the new line only if the username is unique AND the password meets your criteria:
if name_is_unique and password_contains_number and password_is_long_enough:
print(cilent,file = f)
Edit: You may also have to open it in reading and writing mode, something like "a+" instead of "a".

Only read first line of a text file

I have a text file named "paintingJobs". The data looks like this:
E5341,21/09/2015,C102,440,E,0
E5342,21/09/2015,C103,290,A,290
E5343,21/09/2015,C104,730,N,0
E5344,22/09/2015,C105,180,A,180
I have written a program that only finds the first entry but cannot find any data beyond the first line (I think it is to do with Python including /n in front of the username) The program looks like this.
def ASearch():
print("Option A: Search for an estimate")
print("Please enter the estimate number: ")
estimateNumber = str(input())
file = open("paintingJobs.txt", "r")
paintJobs = file.readlines()
file.close()
length = len(paintJobs)
paintData = []
for line in paintJobs:
estNumber, estDate, CustID, FinalTotal, Status, AmountPaid = line.split(",")
if estimateNumber == estNumber:
print("Estimate number: ", estNumber)
print("Customer ID: ", CustID)
options()#this is a function in a for a different part of the program that works fine
else:
print("You have entered an incorrect estimate number; please try again")
ASearch()
How do I get the program to read (and return the values of) the second entry in the list E.G. E5342 (any help would be appreciated greatly)

Resources