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
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 days ago.
Improve this question
The problem I am getting is that the file I'm reading, searching, deleting does not exist on the "grocery_note". the code that I need to fix is the .csv file that cannot locate on the computer.
Here is my code:
import os
import re
import csv
from pathlib import Path
print("Welcome to the PDI!")
print("\nWhich stands for PERSONA DETAILS INTERACTIONS")
# Getting the information of the user first before starting the main program.
class Persona:
def __init__(self, Firstname, Middlename, Lastname, Age, Gender, Civil_status, Phone_Number, Telephone_Number, Email_Address, Religion, Language_use, Country, City, Province, Postcode, Street_Name):
self.Firstname = Firstname
self.Middlename = Middlename
self.Lastname = Lastname
self.Age = Age
self.Gender = Gender
self.Civil_status = Civil_status
self.Phone_Number = Phone_Number
self.Telephone_Number = Telephone_Number
self.Email_Address = Email_Address
self.Religion = Religion
self.Language_use = Language_use
self.Country = Country
self.Province = Province
self.City = City
self.Postcode = Postcode
self.Street_Name = Street_Name
# Displaying the user's information
def display_info(self):
print("\nUser's Details:")
print(f"Name: {self.Firstname} {self.Middlename} {self.Lastname}")
print(f"Age: {self.Age} years old")
print(f"Gender: {self.Gender}")
print(f"Civil Status: {self.Civil_status}")
print(f"Phone Number: {'0' + str(self.Phone_Number)}")
print(f"Telephone Number: {self.Telephone_Number}")
print(f"Email Address: {self.Email_Address}")
print(f"Religion: {self.Religion}")
print(f"Language Use: {self.Language_use}")
address = ', '.join([self.Country, self.City + " City", self.Province + " Province", self.Postcode, self.Street_Name])
print(f"Address: {address}")
print()
print("="*30)
a = input("Enter your First Name: ")
x = input("Enter your Middle Name: ")
v = input("Enter your Last Name: ")
b = int(input("Enter your Age: "))
c = input("Enter your Gender (M/F): ")
o = input("Enter your Civil Status: ")
d = int(input("Enter your Phone Number: "))
e = int(input("Enter your Telephone Number: "))
f = input("Enter your Email Address: ")
g = input("Enter your Religion: ")
h = input("Enter your Language Use: ")
i = input("Enter your Country: ")
j = input("Enter your City: ")
k = input("Enter your Province: ")
l = input("Enter your Postcode: ")
m = input("Enter your Street Address: ")
person = Persona(a, x, v, b, c, o, d, e, f, g, h, i, j, k, l, m)
person.display_info()
def create_grocery_file(filepath):
file_path.parent.mkdir(parents=True, exist_ok=True)
with open(file_path, "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Item Name", "Quantity"])
class BankAccount:
def __init__(self, Name, Account_Number, Balance):
self.Name = Name
self.Account_Number = Account_Number
self.Balance = int(Balance)
self.filename = None
def Card(self):
return input("\nDo you want to Enter your Card? (Y/N): ")
def deposit(self, amount):
self.Balance += amount
print(f"\n{str(amount)} was deposited to your account.")
def display_info(self):
return f"\nName: {self.Name}\nAccount Number: {self.Account_Number}\nBalance: {self.Balance}"
def set_filename(self, filename):
self.filename = filename
def write_file(self,text):
with open(self.filename, "w") as f:
f.write(text)
if __name__ == "__main__":
print("\n")
print("=" * 50)
print("\n")
print("="*30)
print("Main Menu")
print("="*30)
print("1. Go to Semi-bank Account ATM")
print("2. Create a note for your Grocery")
print("3. Exit")
print("="*30)
selection = input("\nSelect a number that you want to go: ")
Name1 = input("\nEnter your Name: ")
Account_Number = input("Enter your Pin Number: ")
Balance = input("Enter your Balance: ")
bank_accountsu = BankAccount(Name1,Account_Number,Balance)
bank_accountsu.set_filename("Info of your bank account.txt")
text = bank_accountsu.display_info()
bank_accountsu.write_file(text)
while True:
if selection == "1":
if bank_accountsu.Card().lower() == "y":
print("Your Card is inserted in the Semi-Bank Account ATM")
elif bank_accountsu.Card().lower() == "n":
print("Thank you! for using the Semi-Bank Account ATM")
break
else:
pass
print("\n")
print("="*30)
print("Welcome to Semi-bank Account ATM!")
print("="*30)
print("1. Withdraw")
print("2. Deposit")
print("3. Personal Data Account")
print("4. Exit")
print("="*30)
while True:
option = input("\n Select a Number: ")
if option == "1":
amount = int(input("Enter the amount you want to withdraw: "))
if amount > bank_accountsu.Balance:
print("Insufficient Balance")
else:
bank_accountsu.Balance =- amount
print(f"You have successfully withdraw the amount of {str(amount)}. Your remaining balance is {str(bank_accountsu.Balance)}")
elif option == "2":
amount = int(input("\nEnter the amount you want to deposit: "))
bank_accountsu.deposit(amount)
elif option == "3":
print(bank_accountsu.display_info())
else:
print("\nThank you for using Semi-Bank Account ATM!")
exit()
break
if selection == "2":
grocery_note = input("Enter the name of your grocery note file: ")
file_path = Path.cwd() / "Grocery Notes" / f"{grocery_note}.csv"
file_exists = file_path.exists()
if not file_exists:
file_path.parent.mkdir(parents=True, exist_ok=True)
with open(file_path, "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Item Name", "Quantity"])
while True:
print("\n")
print("="*30)
print("\nWhat would you like to do with your grocery note?")
print("1. Write to grocery note")
print("2. Read grocery note")
print("3. Search grocery note")
print("4. Delete grocery note")
print("5. Exit grocery note")
option = input("\nEnter your choice: ")
if option == "1":
if file_exists:
print(f"Appending to existing file {grocery_note}.csv")
with open(file_path, "a", newline="") as file:
writer = csv.writer(file)
else:
print(f"Creating new file {grocery_note} in Grocery Notes")
file_path.parent.mkdir(parents=True, exist_ok=True)
with open(file_path, "w", newline="") as file:
writer = csv.writer(file)
item = input("Enter the item you want to add to: ")
quantity = input("Enter the quantity:")
with open(file_path, "a", newline="") as file:
writer = csv.writer(file)
writer.writerow([item, quantity])
print("Item added to the grocery note.")
elif option == "2":
if file_exists:
with open(file_path, "r",newline="") as file:
reader = csv.reader(file)
for row in reader:
print(row)
else:
print(f"File {grocery_note} does not exist.")
elif option == "3":
if file_exists:
with open(os.path.join(os.path.expanduser("~"), "Downloads", f"{grocery_note}.csv"), "r") as file:
reader = csv.reader(file)
search_term = input("Enter the item name you want to search: ")
for row in reader:
if search_term.lower() in row[0].lower():
print(row)
found = True
if not found:
print(f"No items found that match {search_term}.")
else:
print(f"File {grocery_note} does not exist.")
elif option == "4":
if file_exists:
os.remove(file_path)
print(f"File {grocery_note} has been deleted.")
else:
print(f"File {grocery_note} does not exist.")
elif option == "5":
print("Thank you for using PDI!")
exit()
break
else:
print("Invalid input.")
[enter image description he(https://i.stack.imgur.com/Xmvo5.png)enter image description here
Here is the problem that says "file does not exist"
Fix the code that I am getting
lstEmployees = []
lstNames = []
counter = 0
def export_employee():
for employee in lstEmployees:
with open("file.txt", "w") as output:
output.write(str(lstEmployees))
def search_uen():
uen = input("Enter employee UEN: ")
for employee in lstEmployees:
if uen == employee[1]:
print("-----------------" + employee[0] + "------------------------")
print("UEN: " + employee[1])
print("Phone: " + employee[2])
print("Email: " + employee[3])
print("Salary: £" + employee[4])
return employee
return -1
def edit_employee():
search = search_uen()
if search == -1:
print("Employee not found...")
else:
name = input("Enter the new name of the employee: ")
uen = input("Enter the new UEN of the employee: ")
phone = input("Enter the Phone number of the employee: ")
email = input("Enter the email of the employee: ")
salary = input("Enter the salary of the employee: ")
search[0] = name
search[1] = uen
search[2] = phone
search[3] = email
search[4] = salary
def add_employee():
global counter
while counter < 5:
print("----------------------------------------------------------\n")
print(" Number of employee ({0:d})" .format(counter))
print("----------------------------------------------------------\n")
name = input("enter employee name: ")
lstNames.insert(counter, name)
uen = input("enter employee UEN: ")
phone = input("enter employee phone number: ")
email = input("enter employee email: ")
salary = input("enter employee salary: ")
lstEmployees.append([name, uen, phone, email, salary])
if counter > 5:
break
else:
continue
def print_employee():
for employee in lstEmployees:
print("-----------------" + employee[0] + "------------------------")
print("UEN: " + employee[1])
print("Phone: " + employee[2])
print("Email: " + employee[3])
print("Salary: £" + employee[4])
def menu():
while True:
print('-------------------------------------------\n')
print('Welcome to the Employee Management System -\n')
print('-------------------------------------------\n')
print('[1] Add An Employee: \n')
print('[2] View All Employees: \n')
print('[3] Search Employees By UEN: \n')
print('[4] Edit Employees Information: \n')
print('[5] Export Employee Records: \n')
user_option = input("Please select an option ")
if user_option == "1":
add_employee()
elif user_option == "2":
print('\n' * 3)
print_employee()
print('\n' * 3)
elif user_option == "3":
found = search_uen()
if found == -1:
print("Employee not found...")
elif user_option == "4":
edit_employee()
elif user_option == "5":
export_employee()
else:
print("Please select valid option...")
if __name__ == "__main__":
menu()
i have no idea what to do here, on line its saying that the variable 'employee' is not used and i dont know why and when i switch the code to make the add_employee function look like this: (see image)code line 7 change
when i run the code i cant add employees and the string will always say 0 even after i have add details in.
other info: im using both latest version of pycharm and python sdk.
You're calling the main() function but there's no main function defined. I think you want to use menu().
Your if __name__ block should look like this:
if __name__ == "__main__":
menu()
Your export_employee function never uses the employee variable in the loop. Every time you just write out the entire list of employees. Below, we open the file before we iterate over the list.
def export_employee():
with open("file.txt", "w") as output:
for employee in lstEmployees:
output.write(str(employee))
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.
I am currently learning Python and I am making a tennis coach program. On the option 3 where you can update it is not working as it says nameUnder is not defined in the else statement. Please help as I really don't understand why its not working. I have also tries it without the split but that to doesn't work
import os, sys
print("Please select an option:")
print("[1] Add a student")
print("[2] Read a students data")
print("[3] Update a students data")
print("[4] Delete a students data")
menuSelect = int(input("Make your number selection: "))
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if menuSelect == 1:
amountDone=0
amounttodo=int(input("Enter the number of contestants you would like to add: "))
while amounttodo>amountDone:
ageOne=int(input("Enter the age of the contestant: "))
if ageOne <= 11:
underFile=open("Under11s.txt","a")
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")
posUnder=int(input("Input the last position of the student: "))
underFile.write("\n"+str(nameUnder) + " | " + str(genderUnder) + " | " + str(posUnder))
underFile.close()
amountDone=amountDone+1
elif ageOne >= 12:
overFile=open("Over11s.txt","a")
nameOver=input("Enter the first name of the student: ")
genderOver=input("Enter the gender of the student: ")
posOver=int(input("Input the last position of the student: "))
overFile.write("\n"+str(nameOver) + " | " + str(genderOver) + " | " + str(posOver))
overFile.close()
amountDone=amountDone+1
else:
print("Invalid, Please enter a number")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
elif menuSelect == 2:
print("Enter the file you would like to open.")
print("1) Under 11's")
print("2) Over 11's")
fileToOpen=int(input("Enter the number of your selection: "))
if fileToOpen == 1:
f = open("Under11s.txt", "r")
file_contents = f.read()
print(file_contents)
elif fileToOpen == 2:
f = open("Over11s.txt", "r")
file_contents = f.read()
print(file_contents)
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
elif menuSelect == 3:
studentName = input("Enter the student name you are looking for:")
file = open("Under11s.txt","r")
found=False
for line in file:
details = line.split(",")
writefile = open("Under11supdated.txt","a")
details = line.split(",")
if details[0] == studentName:
found=True
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")
posUnder=int(input("Input the last position of the student: "))
file.write("\n"+str(nameUnder)[0] + " | " + str(genderUnder)[1] + " | " + str(posUnder)[2])
else:
file.write("\n"+nameUnder[0] + " | " + genderUnder[1] + " | " + posUnder[2])
file.close()
file.close()
os.remove("Under11s.txt")
os.rename("Under11supdated.txt","Under11s.txt")
if found==True:
print("Details updated")
else:
print("That student cannot be found in the file, no changes made")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
else:
print("Sorry, this option is not available yet!")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
nameUnder only gets defined if this statement is true if details[0] == studentName:
Not a 100% of your logic here, but make sure to set nameUnder= "" before the if statement so the variable is declared and can be used in your else clause.
I would recommend you to structure your code with functions for the each options etc., will make it easier to read and possible reuse some of the code.
Partly updated code:
writefile = open("Under11supdated.txt","a")
details = line.split(",")
nameUnder = ""
if details[0] == studentName:
found=True
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")
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()