How to write data to a text file in python? - 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()

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.

Python updating text files

Hi guys i'm making a manager software on python and I came across a problem
I made a an original text file for my software that contains all my data.Now i have an options of 'add' to the data in the software, but I want the data added by the users to go to a separate text file and not disturb the original. Anyone know how?
My code:
stock_file = open('A3_s3899885_stock.txt', 'a')
print("Adding Movie")
print("================")
item_description = input("Enter the name of the movie: ")
item_genre = input("Enter the genre of the movie:")
item_quantity = input("Enter the quantity of the movie: ")
item_price = input("Enter the price of the movie: ")
stock_file.write(item_description + ' ,')
stock_file.write(item_genre + ', ')
stock_file.write(item_quantity + ', ')
stock_file.write(item_price)
stock_file.close()
user_choice = int(input('Enter 7 to continue or 8 to exit: '))
if user_choice == 7:
menu()
else:
exit()```
You need to write the updated text into another file.
# read original data
original_file_path = 'A3_s3899885_stock.txt'
stock_file = open(original_file_path, 'r')
original_data = stock_file.read()
stock_file.close()
# add user data into user_data
user_data = original_data
print("Adding Movie")
print("================")
item_description = input("Enter the name of the movie: ")
item_genre = input("Enter the genre of the movie:")
item_quantity = input("Enter the quantity of the movie: ")
item_price = input("Enter the price of the movie: ")
user_data += item_description + ' ,'
user_data += item_genre + ' ,'
user_data += item_quantity + ' ,'
user_data += item_price + ' ,'
# save user_data into file
user_file_path = ''
user_stock_file = open(user_file_path, 'w')
user_stock_file.write(user_data)
user_stock_file.close()
user_choice = int(input('Enter 7 to continue or 8 to exit: '))
if user_choice == 7:
menu()
else:
exit()

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 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 run a continuous loop and add input to text

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

Categories

Resources