I am trying to write a code which asks a user for a username and password and then stores these into a csv file in 2 seperate columns. I have tried lots of different methods but cannot seem to do it :/
username = input ("What is your first name (or username)? ")
username = (username[0:3])
birthyear = input ("What year were you born? ")
birthyear = (birthyear[2:4])
print (("Your username is ") + (username) + (birthyear))
login = (username) + (birthyear)
newpassword = input ("Please create a password ")
with open ("scores.csv", "a") as scoreFile:
scoreFileWriter = csv.writer(scoreFile)
scoreFileWriter.writerow(username + "," + newpassword+"\n")
scoreFile.close()
This is one way I've tried but it writes every single letter in a different column like this:
b o b , p a s s w o r d
Instead of this:
bob, password
Thanks in advance if you can offer any help :)
You should specify a delimiter of ','. https://docs.python.org/3/library/csv.html
scoreFileWriter = csv.writer(scoreFile, delimiter=',')
Also, storying passwords in plain-text is Very Bad Practice (TM).
It looks like in this line you're doing the comma yourself, that is what the csv writer will do for your (as #Pipupnipup said, specify a delimeter)
You should just pass writerow a list and let it handle the newline and comma:
scoreFileWriter.writerow([username, newpassword])
And to iterate: Storing passwords in plain-text is Very Bad Practice (TM).
Working code:
username = input ("What is your first name (or username)? ")
username = (username[0:3])
birthyear = input ("What year were you born? ")
birthyear = (birthyear[2:4])
print (("Your username is ") + (username) + (birthyear))
login = (username) + (birthyear)
newpassword = input ("Please create a password ")
with open ("scores.csv", "a") as scoreFile:
scoreFileWriter = csv.writer(scoreFile, delimiter=',')
scoreFileWriter.writerow([login, newpassword])
scoreFile.close()
In relation to your stated problem .writerow() requires a sequence ('', (), []).
As you were passing strings not a sequence writerow() iterates over each letter in your string and each letter is written to a separate cell in the CSV. By giving [username, newpassword] you provide a sequence.
Also, note that you are passing the original Username, as the entered string, not the concatenation of username + birthyear which you return to the user as their username.
Related
I'm trying to get my code to check if a word is already in the document. However when choosing a variable (username) that happens to share the same letters going to the right as the preexisting one in the file, it thinks that the name is taken. For example, if abcdefg was in the file, if I was to right defg or fg or g, it would think the username was taken.
def register():
print("━━━━ACCOUNT CREATION━━━━")
username = input("Create Username: ")
with open("Login.txt", "r") as loginfile:
if (username+",") in loginfile.read():
print("Sorry, but that username is taken.")
choice = input("Try again with a new name? (Y/N)")
choice = choice.upper()
My case:
Say I had the name, Joe which is already in the file. If I tried to make a username that is just e, then it would think it is Joe, as it is looking for the e, next to a comma.
Anyway to fix this? Thanks!
This should work
with open('login.txt', 'r') as LoginFile:
# the split function splits a string to a list on mark
Data = LoginFile.read().split(" ,")
if username in Data:
# .....
if this isn't what you want try this built-in module :
https://docs.python.org/3/library/re.html
def register():
print("━━━━ACCOUNT CREATION━━━━")
# read the names from the file
with open('Login.txt', 'r') as f:
names = f.read().split(',')
username = input("Create Username: ")
for name in names:
# check if any names end with this name have been created
if name.endswith(username):
# found
print("Sorry, but that username is taken.")
# we want to keep ask the user to select if
# they enter something other than Y/N
while True:
# ask for the option
option = input("Try again with a new name? (Y/N) ")
# try again, we just rerun this function
if option == 'Y':
register()
# don't ask any more
break
elif option == 'N':
# exit if user chooses N
break
# if the user chooses something else, continue
# the loop and keep asking
# if no names end with username, goto else
break
else:
# name available, save it to the file
print("Name created successfully:", username)
new_names = names + [username]
with open('Login.txt', 'w') as f:
f.write(','.join(new_names))
I have tested it, please try and see if it works for you.
I'm trying to practice my python skills, I knew that I was kind of unfamiliar with how to work with files so I decided to teach my self. The code is basically making an account, signing in and checking the user and pass stored in a file. I know my user and pass is appending and reading to the file. The problem i'm getting is in my if statement. I'm using if i == user but == means literal. So i tried just using one = to check if one variable = the variable that the user has put in, when I do that, I get a syntax error. My last question is when I run the code, in they else statement where it says username incorrect, it says it 2 or 3 times in the console. This confuses me because no where outside of the else statement is their a while or for loop. If someone can just explain how to get my if statment to excutute when the user and password string are right. That would be great. Also if you know why my console is doing the else: print('username incorrect) 3 times for no reason. I'm very curious to know
I tried printing out the variables in my for loop and it indeed printed the strings in the file.
u = open('users.txt', 'a+')
p = open('pass.txt', 'a+')
does_acc = input('Do you have a account? ')
if does_acc == 'no' or does_acc == 'No':
new_user = input('Username: ')
u.write(new_user + '\n')
new_pass = input('Password: ')
p.write(new_pass + '\n')
sign_in = input('Would you like to sign in? ')
if sign_in == 'yes' or sign_in == 'Yes':
n = open('users.txt', 'r')
m = open('pass.txt', 'r')
lines = n.readlines()
line = m.readlines()
user = input('Username: ')
for i in lines:
print(i)
if i = user:
password = input('Password: ')
for x in lines:
if password == x:
print('secret file opened')
else:
print("{} is not a valid password.").format(password)
else:
print('Username incorrect.')
else:
print('Have a nice day.')
u.close()
p.close()
Do you have a account? yes
Would you like to sign in? yes
Bob
Username: Bob
Username incorrect.
Username incorrect.
This if i = user: should be replaced with this: if i == user: (double equal sign)
Once you have created a new account, you should close the files, because you're going to open them again while they are already open. This might or might not lead to a wrongfully read / written data.
The idea that once user has entered their name, the whole password file is matched against the input password does not seem right -- you only need to check the one password for every user.
for x in lines: tries to match the password against the user names. Seems strange.
print("{} is not a valid password.").format(password) has wrong parenthesis order, it should be "string".format(parm) enclosed in print( .... ), not vice versa.
All in all, I'd rather rewrite your password matching part like this:
with open( 'passwords.txt' ) as fin :
passwords = [p.strip() for p in fin.readlines()]
with open( 'users.txt' ) as fin :
users = [u.strip() for u in fin.readlines()]
user = input( 'User: ' )
password = input( 'Password: ' )
if [user, password] in zip( users, passwords ) :
print( "You're welcome!" )
else :
print( "Go away!" )
Or something along the lines.
the if i = user should be if i == user and also you are opening the same file twice, one at the beginning and the second one after if sign_in == 'yes' or sign_in == 'Yes':
I need to make a function for client registration where the client's username must be unique. I made a dict and a list where I put everything from my txt file, and now I've been trying to set for and while loops, but it isn't going well:
client_list = []
def c_l():
with open("svi.txt","r") as f:
pieces = ["username","password","name","lastname","role"]
for r in f.readlines():
dicct = {}
bla = r.strip().split("|")
count = 0
for i in bla:
dicct[pieces[count]] = i
count += 1
client_list.append(dicct)
c_l()
def reg():
for r in client_list:
while True:
username = input("Username: ")
if (username == r["username"] ):
print("Username is already taken, please try again: ")
else:
break
password = input("Your password:")
name = input("Your name: ")
lastname = input("Your lastname: ")
client = username + "|" + password + "|" + name + "|" + lastname + "|" + "buyer"
with open("svi.txt","a") as f:
f.write(client)
reg()
When I was typing this function for the first time, I made all in one function, where I opened the file, typed code for unique username and then printed client into that txt file. In that function my while loop worked, because all I had to do is to split the parts of the file and index the right one, then make this while loop, which worked fine. But now I've been told that I have to do it by using dict and list and I tried doing this, I don't know what the problem is with my approach.
You may want to load usernames into a set which ensures uniqueness. Then, in your reg function check whether the new username is in the set, like:
if username in myset:
raise InvalidUsernameError
else:
myset.add(username)
I need to create a program that saves people's information e.g. their name in a text file depending on the first letter of their surname so if their surname starts with a K it goes into MyFile1.
I need it to loop like I have done because it's an unknown number of people however I want each person to be written in a different line in the text file is there a way to do this.
The code at the bottom puts each separate information into a new line and I don't want that I want each different person to be in a new line.
MyFile1 = open("AL.txt", "wt")
MyFile2 = open("MZ.txt", "wt")
myListAL = ([])
myListMZ = ([])
while 1:
SurName = input("Enter your surname name.")
if SurName[0] in ("A","B","C","D","E","F","G","H","I","J","K","L"):
Title = input("Enter your title.")
myListAL.append(Title);
FirstName = input("Enter your first name.")
myListAL.append(FirstName);
myListAL.append(SurName);
Birthday = input("Enter birthdate in mm/dd/yyyy format:")
myListAL.append(Birthday);
Email = input("Enter your email.")
myListAL.append(Email);
PhoneNumber = input("Enter your phone number.")
myListAL.append(PhoneNumber);
for item in myListAL:
MyFile1.write(item+"\n")
elif SurName[0] in ("M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"):
Title = input("Enter your title.")
myListMZ.insert(Title);
FirstName = input("Enter your first name.")
myListMZ.append(FirstName);
myListMZ.append(SurName);
Birthday = input("Enter birthdate in mm/dd/yyyy format:")
myListMZ.append(Birthday);
Email = input("Enter your email.")
myListMZ.append(Email);
PhoneNumber = input("Enter your phone number.")
myListMZ.append(PhoneNumber);
line.write("\n")
for item in myListMZ:
MyFile2.write(line)
elif SurName == "1":
break
MyFile1.close()
MyFile2.close()
You are looking for join.
When you have a list of items you can join them in a single string with.
l = ['a', 'b', 'c']
print(''.join(l))
produces
abc
You can not only use the empty string but also another string which will be used as separator
l = ['a', 'b', 'c']
print(', '.join(l))
which now produces
a, b, c
In your examples (for example the first write)
MyFile1.write(','.join(MyListAL) + '\n')
If you happen to have something in the list which is not a string:
MyFile1.write(','.join(str(x) for x in MyListAL) + '\n')
(you can also use map, but a generator expression suffices)
Edit: adding the map:
MyFile1.write(','.join(map(str, MyListAL)) + '\n')
In your case I would rather use a list of dictionaries, where a person with all its infos is a dictionary. Then you can convert it to a JSON string, which is a standard format for representing data. (Otherwise you need to define your own format, with delimiters between the items.)
So something like this:
import json # at the top of your script
# I would create a function to get the information from a person:
def get_person_input():
person = {}
person["surname"] = input("Surname: ")
person["title"] = input("Title: ")
person["email"] = input("Email: ")
# TODO: do whatever you still want
return person
# Later in the script when you want to write it to a file:
new_line = json.dumps( person )
myfile.write( new_line + "\n" )
Parsing a json is also very easy after all:
person = json.loads(current_line) # you can handle exception if you want to make sure, that it is a JSON format
You can use in your code for the decision in which array it should be written something like this:
SurName = input("Enter your surname name.")
if SurName[0] <= 'L':
...
else:
...
This will make your script more clear and robust.
I'm basically running a code that builds up an address book into a text file through user entries.
While doing so, I'm checking to see if the inputed information is correct and, in the case that it's not, asking them to correct it. However, I realize that it's possible (though unlikely) that a user could input incorrect information an indefinite number of times and so I'm looking to implement a "while" loop to work around this.
In the case of the code below, I'm basically attempting to have it so that instead of the first ifelse entry I can enter into a loop by checking for the boolean value of "First_Name.isalpha():". However, I can't really think of a way to enter into it as when "First_Name.isalpha():" is true I don't need to enter into the loop as the entry is correct. When it's false, we skip over the loop altogether without having the entry corrected.
That basically prompts the question of whether or not there is a way to enter into a loop for when a boolean value is false. Or, if there's another creative solution that I'm not considering.
Thanks,
A Novice Coder
NewContact = "New Contact"
def NewEntry(NewContact):
# Obtain the contact's information:
First_Name = input("Please enter your first name: ")
Last_Name = input("Please enter your last name: ")
Address = input("Please enter your street address: ")
City = input("Please enter your city of residence: ")
State = input("Please enter the 2 letter abbreviation of your state of residence: ")
ZipCode = input("Please enter your zip code: ")
Phone_Number = str(input("Please enter your phone number: "))
# Ensure all information inputted is correct:
if First_Name.isalpha():
First_Name = First_Name.strip()
First_Name = First_Name.lower()
First_Name = First_Name.title()
else:
First_Name = input("Please reenter your first name. Be sure to to include letters exclusively: ")
if Last_Name.isalpha():
Last_Name = Last_Name.strip()
Last_Name = Last_Name.lower()
Last_Name = Last_Name.title()
else:
Last_Name = input("Please reenter your first name. Be sure to to include letters exclusively: ")
# Organize inputted information:
NewContact = Last_Name + ", " + First_Name
FullAddress = Address + " " + City + ", " + State + " " + ZipCode
# Return information to writer to ensure correctness of information
# Write information onto document
TheFile = open("AddressBook", "w")
TheFile.write(str(NewContact) + "\n")
TheFile.write(str(FullAddress) + "\n")
TheFile.write(str(Phone_Number) + "\n")
TheFile.close()
NewEntry(NewContact)
You're looking for the not operator, which inverts a boolean value:
>>> not False
True
>>> not True
False
>>> not "".isalpha()
True
>>> not "abc".isalpha()
False
You can tack it on the front of any expression that's a valid condition for an if or while.
Use this structure
invalid = True
while invalid:
## get inputs
## validate inputs
## set invalid accordingly