how to run a continuous loop and add input to text - python

I have to run a continuous loop, until the user decides otherwise, which will add the input entered into a text file but i can't seem to get the while loop working properly.
this is what i have so far:
def main():
#Open a file named names.txt.
outfile = open('names.txt', 'w')
#user enters input
fname = input("Enter first name:\t")
lname = input("Enter second name:\t")
telephone = input("Enter telephone number:\t")
print("")
continues = input("Continue? (y = yes):\t")
input_list = [fname, lname, telephone, continues]
outfile.write(fname)
outfile.write(lname)
outfile.write(telephone)
outfile.close()
while continues == 0:
if continues == "y":
fname = input("Enter first name:\t")
lname = input("Enter second name:\t")
telephone = input("Enter telephone number:\t")
print("")
continues = input("Continue?:\t")
outfile.write(fname)
outfile.write(lname)
outfile.write(telephone)
outfile.close()
else:
print("File Written")
#call main
main()
could someone help me out please, i'm using python 3.3.2

You are better wrapping the whole thing in the loop:
Ex:
def main():
while True:
fname = input("Enter first name:\t")
lname = input("Enter second name:\t")
telephone = input("Enter telephone number:\t")
print ("")
continues = input("Continue? (y = yes):\t").lower() # y to break the loop
input_list = [fname, lname, telephone, continues]
if continues == 'y':
with open('names.txt', 'w') as outfile:
# write things to outfile.
# The with block auto closes
# the file after it's statements
print ('File Written')
break # this is how you exit the loop
EDIT:
maybe this line would make more sense:
continues = input("Write to File? (y = yes):\t").lower()

Here is a loop that is working. Can you try it and adapt it to your case?
run = None
while run != 'n':
run = raw_input('continue? [y/n]').lower()

From what I can understand, just try :
continues='y'
while 1:
if continues == "y":
fname = input("Enter first name:\t")
lname = input("Enter second name:\t")
telephone = input("Enter telephone number:\t")
print("")
continues = input("Continue?:\t")
outfile.write(fname)
outfile.write(lname)
outfile.write(telephone)
outfile.close()
else:
print("File Written")
break

Related

How to delete an indicated line in txt file with usage of DELETE Function in Python

I am a student and have a task to create a contact book with usage of oop, functions, txt file , import os.
I just decided to create a book with usage of functions and txt file.
And ...I have faced with some problem of deleting the indicated line (record) in txt file. I have tried many variations of how to do it. Result: delete an all information in the file or just last line, or simply read file and thats all. All I need is to delete a record as per indicated input(word/name).
my tutor edvised me to use a del function :
if each_contact.name==name:
del list_contacts[i]
but i have no idea how to use this function at all. What the logic should be?
my code is like:
def del_contact_name():
## It should delete the required line as per name if txt file
del_name=input('Enter first name for delete this contact record: ')
del_name=del_name.title()
with open(file_name, "r") as f:
file_delete = f.readlines()
with open(file_name, "w") as f:
for line in file_delete:
if line != del_name:
f.write(line)
print("Your Required Contact Record is deleted:", end=" ")
break
and this is just delete only last line if I write a 3 lines of records ( it works, but i need another result). If I do an one record it will not delete but read the line.
The full work looks like this:
file_name = "phonebook.txt"
filerec = open(file_name, "a+")
filerec.close
def show_main_menu():
## General menu
print("\n Phone Book \n"+
" my task and projects \n"+
"=================================\n"+
"Enter 1,2,3,4 or 5:\n"+
" 1 To Display Contacts Records\n" +
" 2 To Add a New Contact Record\n"+
" 3 To Search Contacts\n"+
" 4 To Delete Contacts\n"+
" 5 To Quit\n=========================")
choice = input("Enter your choice: ")
if choice == "1":
filerec = open(file_name, "r+")
file_contents = filerec.read()
if len(file_contents) == 0:
print("Phone Book is Empty")
else:
print (file_contents)
filerec.close
entry = input("Press Enter to continue ...")
show_main_menu()
elif choice == "2":
enter_contact_record()
entry = input("Press Enter to continue ...")
show_main_menu()
elif choice == "3":
search_contact_record()
entry = input("Press Enter to continue ...")
show_main_menu()
elif choice=='4':
del_contact_name()
entry=input("Press Enter to continue ...")
show_main_menu()
elif choice== "5":
print("Thanks for using Phone Book Programm ")
else:
print("Wrong choice, Please Enter [1 to 5]\n")
entry = input("Press Enter to continue ...")
show_main_menu()
def search_contact_record():
##' This function is used to searches a specific contact record
search_name = input("Enter First name for Searching contact record: ")
search_name = search_name.title()
filerec = open(file_name, "r+")
file_contents = filerec.readlines()
found = False
for line in file_contents:
if search_name in line:
print("Your Searched Contact Record is:", end=" ")
print (line)
found=True
break
if found == False:
print("There's no contact Record in Phone Book with name = " + search_name )
def enter_contact_record():
## It collects contact info firstname, last name, notes and phone
first = input('Enter First Name: ')
first = first.title()
last = input('Enter Last Name: ')
last = last.title()
phone = input('Enter Phone number: ')
notes = input('Enter notes: ')
contact = ("[" + first + " " + last + ", " + phone + ", " + notes + "]\n")
filerec = open(file_name, "a")
filerec.write(contact)
print( "This contact\n " + contact + "has been added successfully!")
def del_contact_name():
## It should delete the required line as per name in txt file
del_name=input('Enter first name for delete this contact record: ')
del_name=del_name.title()
with open(file_name, "r") as f:
file_delete = f.readlines()
with open(file_name, "w") as f:
for line in file_delete:
if line != del_name:
f.write(line)
print("Your Required Contact Record is deleted:", end=" ")
break
show_main_menu()
file_name = "phonebook.txt"
def show_main_menu():
## General menu
print("\n Phone Book \n"+
" my task and projects \n"+
"=================================\n"+
"Enter 1,2,3,4 or 5:\n"+
" 1 To Display Contacts Records\n" +
" 2 To Add a New Contact Record\n"+
" 3 To Search Contacts\n"+
" 4 To Delete Contacts\n"+
" 5 To Quit\n=========================")
choice = input("Enter your choice: ")
if choice == "1":
show_file()
entry = input("Press Enter to continue ...")
show_main_menu()
elif choice == "2":
add_file()
entry = input("Press Enter to continue ...")
show_main_menu()
elif choice == "3":
search_file()
entry = input("Press Enter to continue ...")
show_main_menu()
elif choice=='4':
dell_file()
entry=input("Press Enter to continue ...")
show_main_menu()
elif choice== "5":
print("Thanks for using Phone Book Programm ")
else:
print("Wrong choice, Please Enter [1 to 5]\n")
entry = input("Press Enter to continue ...")
show_main_menu()
def initials():
first = input('Enter First Name: ')
first = first.title()
last = input('Enter Last Name: ')
last = last.title()
phone = input('Enter Phone number: ')
notes = input('Enter notes: ')
contact = ("[" + first + " " + last + ", " + phone + ", " + notes + "]\n")
return contact
def show_file():
#show file
filerec = open(file_name, "r+")
file_contents = filerec.read()
if len(file_contents) == 0:
print("Phone Book is Empty")
else:
print (file_contents)
filerec.close()
def add_file():
#add text to a file
with open(file_name, 'a') as f:
f.write(initials())
f.close()
def search_file():
##' This function is used to searches a specific contact record
search_name = input("Enter First name for Searching contact record: ")
# If you enter not a name, but a sign that is in the record, then he will find it
search_name = search_name.title()
filerec = open(file_name, "r+")
file_contents = filerec.readlines()
found = True
for line in file_contents:
if search_name in line:
print("Your Searched Contact Record is:", end=' ')
print (line)
found=False
break
if found:
print("There's no contact Record in Phone Book with name = " + search_name )
filerec.close()
def dell_file():
## It should delete the required line as per name in txt file
del_name=input('Enter first name for delete this contact record: ')
del_name=del_name.title()
count_str = 0
no_string = True
with open(file_name, "r+") as file:
lines = file.readlines()
for i in lines:
count_str +=1
if del_name in i:
no_string = False
del lines[count_str-1]
break
if no_string:
print('No line')
with open(file_name, "w") as file:
file.writelines(lines)
file.close()
show_main_menu()
Now the deletion is working.

Is there a better way to check if a series of inputs match a certain stop condition?

(Python 3.7)
I have a similar program to what's included below. I was just trying to figure out if there is a better way to check if any user input matches an "end" condition, I do need to save each input separately.
while True:
fname = input("Enter Customer first name: ")
if fname == "end":
break
lname = input("Enter Customer last name: ")
if lname == "end":
break
email = input("Enter Customer email: ")
if email == "end":
break
num = input("Enter Customer id: ")
if num == "end":
break
elif not num.isdigit():
num = -1
# not worried about error here
num = int(num)
print(fname, lname, email, num)
print("User has ended program")
I'm not worried about errors at this stage just trying to brainstorm here about the cleanest implementation. I will have a lot of inputs so I'm hoping I won't have to include the same if statement over and over again for each individual input.
This would be a good opportunity to create a user exception:
class UserExit(BaseException):
pass
def get_input(prompt):
response = input(prompt)
if response=="end":
raise UserExit("User Exit.")
return response
try:
while True:
fname = get_input("Enter Customer first name: ")
lname = get_input("Enter Customer last name: ")
email = get_input("Enter Customer email: ")
num = get_input("Enter Customer id:")
if not num.isdigit():
num = -1
else:
num = int(num)
print (fname,lname,email,num)
except UserExit as e:
print ("User ended program.")

Python: Add an entry in a file and assign an ID automatically

I'm writing a program that prompts users to do some things, and one of those is add a user by prompting user details. The file.txt is as the image below, but I'm stack on how to actually make the user ID work. The next users added should take ID numbers 5, 6, 7, and so on.
When I run the programme, the ID assigned is random. Can you please advice?
The text file is as below: (I'm a beginner in this please be detailed)
file.txt
def new_user():
file = open('file.txt', 'r+')
lines = file.read()
newid = len(lines)
addUserDetail(newid)
file.close()
def addUserDetail(newid):
firstname = input("Please enter first name: ")
secondname = input("Please enter surname: ")
address1 = input("Please enter house number and street name: ")
address2 = input("Please enter city: ")
postcode = input("Please enter postcode: ")
telephonenumber = input("Please enter telephone number: ")
file = open('file.txt', 'r')
line = file.readlines()
count = len(line)
newcount = len(line)+1
newline=("\n" + str(newcount) + " " + firstname + " " + secondname + " " + address1 + " " + address2 + " " + postcode + " " + telephonenumber)
file = open('file.txt', 'a')
file.write(newline)
file.close()
while True:
print("1 - Input for new user")
print("2 - Close the programme")
option = int(input("Option: "))
if option == 1:
new_user()
elif option == 2:
print("See you")
exit(2)
else:
print("Your option is incorrect")
Although I am not entirely sure if I understood your problem correctly, I am assuming that you would like to use newid in addUserDetail before writing the values back.
The newid inside the new_user function isn't actually taking an arbitrary value. It equals the number of characters in the file. This is because of the file.read() returns type str. This can be fixed by using the readlines() function.
The code for the same is as follows:
def new_user():
file = open('file.txt', 'r+')
lines = [i.strip() for i in file.readlines()]
newid = len(lines)
addUserDetail(newid)
file.close()
def addUserDetail(newid):
firstname = input("Please enter first name: ")
secondname = input("Please enter surname: ")
address1 = input("Please enter house number and street name: ")
address2 = input("Please enter city: ")
postcode = input("Please enter postcode: ")
telephonenumber = input("Please enter telephone number: ")
file = open('file.txt', 'r')
line = file.readlines()
newline = ("\n" + str(newid+1) + " " + firstname + " " + secondname + " " + address1 + " " + address2 + " " + postcode + " " + telephonenumber)
file = open('file.txt', 'a')
file.write(newline)
file.close()
while True:
print("1 - Input for new user")
print("2 - Close the programme")
option = int(input("Option: "))
if option == 1:
new_user()
elif option == 2:
print("See you")
exit(2)
else:
print("Your option is incorrect")
I wrote an example for leveraging comma-separated-value (CSV) files for holding your data. This can be better than simply writing data with spaces because its easier to read back later. What do you do when the address itself has spaces?
Python has a handy csv module that can help with the details. So, here is your problem reworked. This isn't exactly the answer, but an alternate option.
import csv
import os
def new_user():
# removed id generation... let add the called routine that updated
# the database do that
addUserDetail()
def addUserDetail():
firstname = input("Please enter first name: ")
secondname = input("Please enter surname: ")
address1 = input("Please enter house number and street name: ")
address2 = input("Please enter city: ")
postcode = input("Please enter postcode: ")
telephonenumber = input("Please enter telephone number: ")
if not os.path.exists('file.txt'):
with open('file.txt', 'w'):
pass
with open('file.txt', 'r+') as file:
user_id = len(file.readlines()) + 1
writer = csv.writer(file)
writer.writerow([user_id, firstname, secondname, address1,
address2, postcode, telephonenumber])
file.close()
while True:
print("1 - Input for new user")
print("2 - Close the programme")
option = int(input("Option: "))
if option == 1:
new_user()
elif option == 2:
print("See you")
exit(2)
else:
print("Your option is incorrect")
The output from adding 2 users is
1,Jen,Dixon,1 A Street,Big City,99999,111-111-111
2,Bradly,Thompson,99 Elm,Small Town,222,9999

I am having trouble writing into a text file because it says my line should be an str and not an int

print("Welcome to English, please enter your name,age,and password.")
print("If you have previously signed in, enter using the same name,age,and password")
name = input("Please enter your name: ")
age = input("Now please enter you age: ")
username = name[0:3] + age
password = input("Now please create a password: ")
userpass = (username+","+password)
check = open("logins.txt")
string = check.read().strip().split()
if userpass in string:
print("You have logged in as",username,"The questions will now start. \n")
else:
newlog = input("Looks like you dont have an account with those details, Would you like to create a new one? Y/N: ")
if newlog == "Y" or newlog == "y" or newlog == "yes" or newlog == "Yes":
f = open("logins.txt","a+")
chosen = f.write(username+","+password+"\n")
print("The username",username,"and password",password,"have now been saved, the questions will now start \n")
f.close()
else:
print("Please either sign in or log in and try again.")
welcome()
import random
f = open("English.txt","r")
points = 0
for line in f:
currentLine = line.split(",")
q = currentLine[0]
answer = currentLine[1]
questions = currentLine[1:-1]
random.shuffle(questions)
print(q)
for i in range(len(questions)):
print (i+1,":",questions[i])
userAnswer = int(input("Make a selection :"))
if answer == questions[userAnswer-1]:
points = (points+1)
print ("CORRECT, You have",points,"points")
str(points)
else:
print ("INCORRECT")
f.close()
f = open("scores.txt","a+")
score = f.write(username+","+password+","+points+"\n") #It is giving a type error about this line and I cant seem to understand why
f.close()
The error shown is:
line 193, in english
score = (username+","+password+","+points+"\n")
TypeError: must be str, not int
Please let me know if you have a better way of writing the scores into a text file. THank you.
Replace the error line with: score = f.write(username+","+password+","+str(points)+"\n")

How to write data to a text file in python?

This is what I have so far:
def main():
infoList = []
count = 0
while True:
firstname = input('Please enter your first name: ')
mystring = str(firstname)
lastname = input('Please enter your last name: ')
mystring2 = str(lastname)
telephoneno = input('Please enter your telephone number: ')
mystring3 = str(telephoneno)
contiinue = input('Continue (y = yes): ')
if contiinue == 'y':
count = count + 1
else:
print ("File Written")
break
file = open('filename', 'a');
file.write(data.to_string());
file.close();
main()
I'm trying to get the program to write the input as a text file, but allow new information added to be added to the text file, not to erase whats already been written.
Every time I try to run the program it say that there's a problem with the main() and also a name error, as data is not defined?
To add to #Clodion's answer I would use the with keyword
def main():
infoList = []
count = 0
while True:
fnane = input('Please enter your first name: ')
lname = input('Please enter your last name: ')
tele = input('Please enter your telephone number: ')
ok = input('Continue (y = yes): ')
if ok == 'y':
count = count + 1
else:
print ("File Written")
break
data = fname + lname + tele
with open('filename', 'a') as file:
file.write(data);
main()
Try:
def main():
infoList = []
count = 0
while True:
mystring = input('Please enter your first name: ')
mystring2 = input('Please enter your last name: ')
mystring3 = input('Please enter your telephone number: ')
contiinue = input('Continue (y = yes): ')
if contiinue == 'y':
count = count + 1
else:
print ("File Written")
break
data = mystring + mystring2 + mystring3
file = open('filename', 'a');
file.write(data);
file.close();
main()
There is a space before main()
my_file = '/home/user/file.txt'
def add_code(my_file, permission, code):
f = open(my_file, permission)
f.write(code + '\n')
f.close()
def main():
infoList = []
count = 0
while True:
mystring = input('Please enter your first name: ')
add_code(my_file, 'a+', mystring)
mystring2 = input('Please enter your last name: ')
add_code(my_file, 'a+', mystring2)
mystring3 = input('Please enter your telephone number: ')
add_code(my_file, 'a+', mystring3)
contiinue = input('Continue (y = yes): ')
if contiinue == 'y':
count = count + 1
else:
print ("File Written")
break
main()

Categories

Resources