I am trying to use subroutines and text files to record and output student data but i have an infinite loop for option 1,2 and 4 and have no idea how to fix it
My code:
def displayMenu():
print("1. save to new file")
print("2. append to and existing file")
print("3. calculate the average mark")
print("4. display data")
choice = input("enter choice")
while int(choice) <1 or int(choice) >5:
choice = input("pick a valid option")
return choice
def saveToFile(a):
studentMark = "0"
studentName = input("enter a student name, type xxx when you are done")
while studentName != "xxx":
file = open ("studentMark.txt", "w")
f = open("studentNames.txt", "w")
studentMark = input("Enter mark:")
f.write(studentName +"\n")
file.write(studentMark + "\n")
studentName = input("name")
f.close()
file.close()
def appendToFile(b):
studentMark = "0"
studentName = input("enter a student name, type xxx when you are done")
while studentName != "xxx":
file = open ("studentMark.txt", "a")
f = open("studentNames.txt", "a")
studentMark = input("Enter mark:")
f.write(studentName +"\n")
file.write(studentMark +"\n")
studentName = input("name")
f.close()
file.close()
def average(c):
total = 0.0
length = 0.0
average = 0.0
file2 = open("studentMark.txt", "r")
for line in file2:
amount = float(studentmark)
total += amount
length = length + 1
average = total / length
print("Average mark:", average)
file2.close()
def printstuff(d):
o = open('output.txt', 'w')
fh = open("studentNames.txt", "r")
fh2 = open("studentMark.txt", "r")
for line in (fh.readlines()):
o.write(line.strip("\r\n") + "\t" + fh2.readline().strip("\r\n") + "\n")
o.close()
o = open("output.txt", "r")
output = o.read()
print(output)
fh.close()
fh2.close()
o.close()
option = displayMenu()
while option != "5":
if option == "1":
saveToFile("write")
elif option == "2":
appendToFile("append")
elif option == "3":
average("mark")
elif option == "4":
printstuff("display")
print("quit")
The calculating averages section of my code is copy and edited from a forum so there may be some outdated code and stuff
I created an infinite loop by not allowing the user to change their option
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
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.
So I want to create a program that takes input of some number of items and adds them to a text file. But I have encountered two problems. One, I don't know how to keep the program running until the user chooses to close it. Two, after the items are added to the text file and then displayed on the screen, it doesn't show the items in the correct order and some are even repeated and other left out. Below is my code, sorry if it's terrible I'm new to this. I had entered the letters s, i, c, and k, with each letter as an item and stored it to the text file and it returned this:
s
s
i
s
i
c
Here's my code
items = []
i= 0
ans = ""
print("Options:\n1: View existing items\n2: Add to list of items\n3: Clear saved items\n4: Make new list\n5. Exit program")
ans = input("\nWhat would you like to do?: ").strip()
if ans == "1":
f = open("items.txt", "r")
print(f.read())
f.close
elif ans == "2":
i = int(input("How many items would you like to enter: ").lower())
for i in range(i):
item = input("Enter the name of item: ").lower()
items.append(item)
f = open("items.txt", "a")
for item in items:
f.write(""+str(item)+"\n")
f.close
elif ans == "3":
f = open("items.txt", "r+")
f.truncate(0)
f.close
elif ans == "4":
i = int(input("How many items would you like to enter: ").lower())
for i in range(i):
item = input("Enter the name of item and price: ").lower()
items.append(item)
f = open("items2.txt", "w")
for item in items:
f.write(""+str(item)+"\n")
f.close
elif ans == "5":
quit()
else:
print("Choose by entering either 1, 2, 3 or 4.")
You'd do something like this:
# to write to a file
number_of_inputs = int(input("How many lines would you like to enter? "))
with open("inputs.txt", "w") as file:
for i in range(number_of_inputs):
file.write(
input("What would you like to write on line %s? " % (i))
+ "\n"
)
# to read from the file
with open("inputs.txt", "r") as file:
for line in file.readlines():
print(line)
I've come to this :
items = []
i = 0
leave = False
while leave is False:
print("Options:\n"
"1: View existing items\n"
"2: Add to list of items\n"
"3: Clear saved items\n"
"4: Make new list\n"
"5. Exit program\n")
ans = input("What would you like to do ? ").strip()
if ans == "1":
with open("items.txt", "r") as f:
print(f.read())
elif ans == "2":
i = int(input("How many items would you like to enter : "))
items = [input("Enter the name of item : ").lower() for i in range(i)]
with open("items.txt", "a") as f:
for item in items:
f.write("{}\n".format(item))
elif ans == "3":
with open("items.txt", "r+") as f:
f.truncate(0)
elif ans == "4":
i = int(input("How many items would you like to enter: ").lower())
items = [input("Enter the name of item and price: ").lower() for i in range(i)]
with open("items2.txt", "w") as f:
for item in items:
f.write("{}\n".format(item))
elif ans == "5":
leave = True
else:
print("Choose by entering either 1, 2, 3 or 4.")
To keep the program running until the user choose to close it you can use a while loop with a leave variable which takes the value True in case the user decides to quit the program by answering 5.
To open your files you should use the with statement.
That code works but it's not perfect because it does not give the user the choice to choose which file (list) to read and show on the screen so you can only have one list. To make it possible for the user to choose between the files you should use the os module.
Which brings us to that code :
import os
os.chdir("itemsFolder")
items = []
i = 0
leave = False
while leave is False:
print("Options:\n"
"1: View existing items\n"
"2: Add to list of items\n"
"3: Clear saved items\n"
"4: Make new list\n"
"5. Exit program\n")
ans = input("What would you like to do ? ").strip()
if ans == "1":
fileName = input("Which list would you like to consult : {} ".format(os.listdir()))
if os.path.exists(fileName):
with open(fileName, "r") as f:
print(f.read())
else:
print("No such list of item exists.")
elif ans == "2":
fileName = input("Which list would you like to consult : {} ".format(os.listdir()))
if os.path.exists(fileName):
i = int(input("How many items would you like to enter : "))
items = [input("Enter the name of item : ").lower() for i in range(i)]
with open(fileName, "a") as f:
for item in items:
f.write("{}\n".format(item))
else:
print("No such list of item exists.")
elif ans == "3":
fileName = input("Which list of items would you like to clear : {} ".format(os.listdir()))
if os.path.exists(fileName):
with open(fileName, "r+") as f:
f.truncate(0)
else:
print("No such list of item exists.")
elif ans == "4":
fileName = input("What do you want to call your new list : ").lower()
i = int(input("How many items would you like to enter: ").lower())
items = [input("Enter the name of item and price: ").lower() for i in range(i)]
with open(fileName + '.txt', "w") as f:
for item in items:
f.write("{}\n".format(item))
elif ans == "5":
leave = True
else:
print("Choose by entering either 1, 2, 3 or 4.")
You should use this tree structure in your project to use the code above :
ProjectFolder
|
-main.py
-itemsFolder
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()