writing a text file on python - python

import time
def mainmenu ():
print ("1.set values")
print ("2. run formula")
print ("3. export formula results")
maininput = int(input("Enter: "))
if maininput == 1:
set_values ()
elif maininput == 2:
formula ()
elif maininput == 3:
export ()
def set_values ():
set_values.first = int(input("Value 1 between 1 and 10"))
while 1< set_values.first <10:
set_values.second = int(input("Value 2 between 1 and 10"))
while 1< set_values.second <10:
mainmenu ()
else:
print ("That is not a valid value")
return set_values ()
def formula ():
part_1 = set_values.first + set_values.second
print ("Value 1 + value 2 =",part_1)
time.sleep(2)
part_2 = part_1 * 5
print ("Value 1 + value 2 x 5 =",part_2)
time.sleep(2)
def export ():
print ()
mainmenu ()
What code would I use in def export to replace print () so the data printed in formula is written to a text file.
Before the data is written the user should be asked to enter a file name and the code should check if a file with the same name exists and if so ask the user if it should be overwritten. If the user chooses not to overwrite the file they should be returned to the part where they enter the file name.

You should consult the documentation for open and write (link here). Outside of that, the preferred method for writing to a file is the following:
with open('myfile.txt', 'w') as f:
f.write('Writing to files is easy')

This is how to print to a txt file:
file = open("Exported.txt", "w")
file.write("Text to write to file")
file.close()
Another way to do so would to be:
with open('Exported.txt', 'w') as file:
file.write("Text to write to file")
This is a program I made to write a txt file:
import os.path
def start():
print("What do you want to do?")
print(" Type a to write a file")
print(" Type b to read a file")
choice = input(" -")
if choice == "a":
create()
elif choice == "b":
read()
else:
print("Incorrect spelling of a or b\n\n")
start()
def create():
print()
filename = input("What do you want the file to be called?\n")
if os.path.isfile(filename):
print("This file already exists")
print("Are you sure you would like to overwrite?")
overwrite = input("y or n")
if overwrite == "y":
print("File has been overwritten")
write(filename)
else:
print("I will restart the program for you")
elif not os.path.isfile(filename):
print("The file has not yet been created")
write(filename)
else:
print("Error")
def write(filename):
print()
print("What would you like the word to end writing to be?")
keyword = input()
print("What would you like in your file?")
text = ""
filename = open(filename, 'w')
while text != keyword:
filename.write(text)
filename.write("\n")
text = input()
def read():
print()
print("You are now in the reading area")
filename = input("Please enter your file name: -")
if os.path.isfile(filename):
filename = open(filename, 'r')
print(filename.read())
elif not os.path.isfile(filename):
print("The file does not exist\n\n")
start()
else:
print("Error")
start()

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.

Cannot load or save txt. file

I wrote a code but apparently It does not save and load to my txt. file. I would greatly appreciate if you took a look into my code and told me what's wrong because I am having really hard time figuring it out myself. I didnt use pickle, as It was creating encoding related difficulties so I tried to find the other way around it and all which saves into my txt. file is "None". Thank you in advance.
def savedata(x):
play_again = input("Are you willing to save existing progress? Y/N")
if (play_again == "Y") or (play_again == "y"):
print("Saving progress...")
file = open('adam_malysz.txt', 'w')
file.write(str(x))
file.close()
print("Your file has been called - adam_malysz.txt")
print("Progress has been successfully saved.")
else:
print("Returning to main menu")
def arrayfancy():
num1 = int(input("Select size of an array: "))
value = []
for i in range(num1):
value.append(random.randint(1, 99))
print("Printing data...")
print(value)
print("Sorting Array...")
bubblesort(value)
print(value)
print("Average value is: ")
print(statistics.mean(value))
print("Minimum value is: ")
print(min(value))
print("Maximum value is: ")
print(max(value))
print("Your data has been successfully printed")
if choice == 1:
savedata(arrayfancy())
Your arrayfancy() has no return statement, so it returns None when it reach the end of the function block. savedata(x) then successfully write "None" to your file.
You can add return value at the end of arrayfancy(), this will solve your issue.
I tested the code bellow and I get the text file containing the array.
def savedata(x):
play_again = input("Are you willing to save existing progress? Y/N")
if (play_again == "Y") or (play_again == "y"):
print("Saving progress...")
file = open('adam_malysz.txt', 'w')
file.write(str(x))
file.close()
print("Your file has been called - adam_malysz.txt")
print("Progress has been successfully saved.")
else:
print("Returning to main menu")
def arrayfancy():
num1 = int(input("Select size of an array: "))
value = []
for i in range(num1):
value.append(random.randint(1, 99))
print("Printing data...")
print(value)
print("Sorting Array...")
bubblesort(value)
print(value)
print("Average value is: ")
print(statistics.mean(value))
print("Minimum value is: ")
print(min(value))
print("Maximum value is: ")
print(max(value))
print("Your data has been successfully printed")
return value
if choice == 1:
savedata(arrayfancy())

Issues loading text file

This code has an error on the load function but I don't understand what is causing it. I'm importing the class definition from another file, the program does save the file as a text in my computer and the program tells me that it loads the data but when I try to call for a display of the data that's when I'm getting the error.
from roster2 import rosterClass
outFile = open("c:\roster.txt", "wt")
outFile.write("The text and data will be save as a file on c:\roster.txt")
outFile.close()
inFile = open("c:\roster.txt", "rt")
contents = inFile.read()
print (contents)
def saveData(roster):
filename = input("Enter file name:")
print("Saving file.....")
outFile = open(filename, "wt")
for x in roster.keys():
name = roster[x].getname()
phone = roster[x].getphone()
jersey = str(roster[x].getjersey())
outFile.write(name+","+phone+","+jersey+"\n")
print("File saved.")
outFile.close()
def loadData():
roster = {}
filename = input("Enter file to load: ")
inFile = open(filename, "rt")
print("Loading data......")
while True:
inLine = inFile.readline()
if not inLine:
break
inLine = inLine[:-1]
name, phone, jersey = inLine.split(",")
roster[name] = name, phone, jersey
print("Roster data loaded succesfully")
inFile.close()
return roster
def displayMenu():
print ("======Main Menu======")
print ("1. Display roster ")
print ("2. Add player:")
print ("3. Remove player: ")
print ("4. Edit player information.")
print ("5. Save data.")
print ("6. Load data.")
print ("9. Exit Program")
print ("")
return int(input("Select a number to continue: "))
def printRoster(roster):
if len(roster) == 0:
print ("no current players in roster")
else:
for x in roster.keys():
roster [x].displayData()
def addRoster (roster):
newName = input("Enter new player's name:")
newPhone = input("Player's phone number: ")
newJersey = int(input("Player's jersey number:"))
roster[newName] = rosterClass (newName, newPhone, newJersey )
return roster
def removeRoster(roster):
removeName = input("enter player's name to be removed:")
if removeName in roster:
del roster[removeName]
else:
print("player not found in list.")
return roster
def editroster(roster):
oldName = input("Enter the name of the player you want to edit:")
if oldName in roster:
newName = input ("Enter the new player's name:")
newPhone = input("Player's new phone number:")
newJersey = int(input("Player's new jersey number:"))
roster[oldName] = rosterClass (newName, newPhone, newJersey)
else:
print ("no player exist in roster")
return roster
print ("Welcome to the Roster Manager")
roster = {}
menuSelection = displayMenu()
while menuSelection !=9:
if menuSelection == 1:
printRoster(roster)
elif menuSelection == 2:
roster = addRoster(roster)
elif menuSelection == 3:
roster = removeRoster(roster)
elif menuSelection == 4:
roster = editRoster(roster)
elif menuSelection == 5:
roster = saveData(roster)
elif menuSelection == 6:
roster = loadData()
menuSelection = displayMenu()
print ("Goodbye......")
I have taken the liberty of attempting to correct the indentation of your code so that it compiles. Of course it won't run on my computer because I don't have the code that your code imports. However, the diagnostic message you supplied complains that, in ' line 62, in printRoster roster [x].displayData() AttributeError: 'tuple' object has no attribute 'displayData''.
The only place in your code that displayData appears is in this line of code:
roster [x].displayData()
It matches the error message! The message says that roster[x] is a tuple which raises my curiosity. How is roster[x] defined?
Two different ways:
roster[name] = name, phone, jersey
roster[newName] = rosterClass (newName, newPhone, newJersey )
I've been programming for nearly fifty years, I can guess which way is correct. What do you think?

I keep getting infinite loops in my subroutines, can someone help me?

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

How to search and store the line number of which in the data was found? (Python)

I am currently developing a program for my local charity and would like to ask how to get the program to
1) Search a notepad file for a specific Word(s)
2) Store which line that the name was found on
My code so far :
import time
def AddToDatabase():
print ("\nYou are adding to the Database. \nA)Continue \nB)Go Back")
ATD = input(": ")
if ATD == "A" or ATD == "a":
Name = input("\nEnter Name of Member [First Name and Surname]: ")
with open("Name.txt", "a") as N:
N.write("\n{}".format(Name))
time.sleep(1)
print ("\nAdding...")
time.sleep(1)
print ("\nEnter Address of "+Name+" all on one line")
print ("In format [Include Commas]")
print ("\nRoad name with house number [e.g. 1 Morgan Way], Borough [e.g Harrow], City [e.g London], Postcode [e.g. HA5 2EF]")
Address = input("\n: ")
with open("Address.txt", "a") as A:
A.write("\n{}".format(Address))
time.sleep(1)
print ("\nAdding...")
time.sleep(1)
Home_Number = input("\nEnter Home Number of "+Name+": ")
with open("Home Number.txt", "a") as HN:
HN.write("\n{}".format(Home_Number))
time.sleep(1)
print ("\nAdding...")
time.sleep(1)
Mobile_Number = input ("\nEnter Mobile Number of "+Name+": ")
with open("Mobile Number.txt", "a") as MN:
MN.write("\n{}".format(Mobile_Number))
time.sleep(1)
print ("\nAdding...")
time.sleep(1)
Email_Address = input ("\nEnter Email Address of "+Name+": ")
with open("Email Address.txt", "a") as EA:
EA.write("\n{}".format(Email_Address))
time.sleep(1)
print ("\nAdding...")
time.sleep(1)
Dietry_Needs = input("\nEnter Medical/Dietry Needs of "+Name+": ")
with open("Medical Dietry Needs.txt", "a") as MDN:
MDN.write("\n{}".format(Dietry_Needs))
time.sleep(1)
print ("\nAdding...")
time.sleep(1)
print ("All information for "+Name+" has been added. Redirecting Back To Main...")
time.sleep(5)
Main()
elif ATD == "B" or ATD == "b":
Main()
def CheckDatabase():
print ("\nSPACE SAVED")
def Main():
print ("\nSVA of UK Database")
while True:
print ("\nA)Check Database \nB)Add to Database \nC)Exit Program")
choice = input(": ")
if choice == "A" or choice == "a":
CheckDatabase()
elif choice == "B" or choice == "b":
AddToDatabase()
elif choice == "C" or choice == "c":
break
else:
print ("Invalid Input")
Main()
Main()
How would try to search for example 'John Smith' in a txt file and store which line that name was found on? I know i may have maybe come across confusing but if you don't get it then please leave a comment and ill answer what you dont get! Thanks in advance!
Pretty basic...
found_line = None
with open(filename) as f:
pattern = "john smith"
for i, line in enumerate(f):
if pattern in line:
found_line = i
print "Found %s in %i" % (pattern, i)

Categories

Resources