How would I tell Python to read my text file? - python

def inputbook():
question1 = input("Do you want to input book?yes/no:")
if question1 == "yes":
author = input("Please input author:")
bookname = input("Please input book name:")
isbn = input("Please input ISBN code")
f = open("books.txt", "a")
f.write("\n")
f.write(author )
f.write(bookname )
f.write(isbn )
f.close()
elif question1 == "no":
input("Press <enter>")
inputbook();
So I have code like this and I when I write last string (isbn), and I want python to read books.txt file. How am i supposed to do it?

There are problems with your open, which renders it unreadable.
You need to open it with:
f = open("books.txt", "+r")
"a" stands for appending, so you won't be able to read books.txt with f.
Second, readlines or readline are not good options for your code as of now. You need to update your write method. Since inside the .txt file, the author, bookname and isbn will be messed together, and you are not able to separate them.

def inputbook():
question1 = raw_input("Do you want to input book? (yes/no):")
if question1 == "yes":
author = raw_input("Please input author:")
bookname = raw_input("Please input book name:")
isbn = raw_input("Please input ISBN code:")
f = open("books.txt", "a+")
f.write("%s | %s | %s\n" % (author, bookname, isbn))
f.close()
elif question1 == "no":
raw_input("Press <enter>")
try:
print open('books.txt', 'r').read()
except IOError:
print 'no book'
if __name__ == '__main__':
inputbook()

Related

Trying to pass in the list of name and number from my contact python code but only save the very last input

import re
contact = {}
def display_contact():
for name, number in sorted((k,v) for k, v in contact.items()):
print(f'Name: {name}, Number: {number}')
#def display_contact():
# print("Name\t\tContact Number")
# for key in contact:
# print("{}\t\t{}".format(key,contact.get(key)))
while True:
choice = int(input(" 1. Add new contact \n 2. Search contact \n 3. Display contact\n 4. Edit contact \n 5. Delete contact \n 6. Save your contact as a file \n 7. Update Saved List \n 8. Exit \n Your choice: "))
if choice == 1:
while True:
name = input("Enter the contact name ")
if re.fullmatch(r'[a-zA-Z]+', name):
break
while True:
try:
phone = int(input("Enter number "))
except ValueError:
print("Sorry you can only enter a phone number")
continue
else:
break
contact[name] = phone
elif choice == 2:
search_name = input("Enter contact name ")
if search_name in contact:
print(search_name, "'s contact number is ", contact[search_name])
else:
print("Name is not found in contact book")
elif choice == 3:
if not contact:
print("Empty Phonebook")
else:
display_contact()
elif choice == 4:
edit_contact = input("Enter the contact to be edited ")
if edit_contact in contact:
phone = input("Enter number")
contact[edit_contact]=phone
print("Contact Updated")
display_contact()
else:
print("Name is not found in contact book")
elif choice == 5:
del_contact = input("Enter the contact to be deleted ")
if del_contact in contact:
confirm = input("Do you want to delete this contact Yes or No? ")
if confirm == 'Yes' or confirm == 'yes':
contact.pop(del_contact)
display_contact
else:
print("Name is not found in phone book")
elif choice == 6:
confirm = input("Do you want to save your contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
with open('contact_list.txt','w') as file:
file.write(str(contact))
print("Your contact-book is saved!")
else:
print("Your contact book was not saved.")
# else:
elif choice == 7:
confirm = input("Do you want to update your saved contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
f = open("Saved_Contact_List.txt" , "a")
f.write("Name = " + str(name))
f.write(" Number = " + str(phone))
f.close()
#with open('contact_list.txt','a') as file:
# file.write(str(contact))
print("Your contact-book has been updated!")
else:
print("Your contact book was not updated.")
else:
break
I have tried but only get to save the last input and not all of the contact list. Any ideas on how to save them all. I have been trying different code as I have comment some out to try a different way but it only print the last input. I would like it to save a output file with the first save to save all the contact then if they add or update a contact to save it as a updated saved file like choice 7. But I only get it to save the last input. I still learning how python works and this is over my head.
You're looking for serialization, which is (usually) best left to libraries. The json library easily handles reading and writing dictionaries to a file.
To write a dictionary, take a look at json.dump():
with open("Saved_Contact_List.txt", "w") as f:
json.dump(contact, f)

Edit a line in a file depending on user's input | Python

I'm working on a contact book application to improve my python skill, so far I've created functions to add new contact, view existing contact, but I'm stuck on a function to edit them, I don't know how to tackle this task (note that editing and adding information is based on user input), currently the only information this application is recording are name, phone number and/or email (if user entered an email).
I'm storing the contacts in individual files, where file name is the contact name, and the contact are his/her information (first line is always the phone number, second line if present is the email) and I'm supposing for now that all contact have phone numbers
As I think that the edit function will be similar to the add, here is the add function
def add_contact():
if question == 'add':
contact_name = input('Enter the name of the contact you want to add: ')
join_input = dir_path + "\\" + contact_name + ".txt"
#join_input = os.joinpath(dir_path, contact_name)
os.makedirs(dir_path, exist_ok=True)
if os.path.exists(join_input):
print('this contact is founded')
else:
while True:
contact_number = input("Enter the contact's number: ")
if not contact_number.isdigit():
print('Type a number next time.')
continue
else:
f = open(join_input, "a")
f.write('Phone number: ' + contact_number)
f.write('\n')
f.close()
email_print = input('Would you like to add an email address? Type yes or no: ').lower()
if email_print == 'yes':
contact_email = input("Enter the contact's email: ")
f = open(join_input, "a")
f.write('Email Adress: ')
f.write(contact_email)
f.close()
print('Contact', contact_name, 'is succesfuly created!')
break
elif email_print == 'no':
print('Contact', contact_name, 'is succesfuly created!')
break
else:
continue
and here is an example of it running
Do you want to add, view, or delete contact? Enter add, view or delete: add
Enter the name of the contact you want to add: test
Enter the contact's number: 0129309123
Would you like to add an email address? Type yes or no: yes
Enter the contact's email: test#gmail.com
Contact test is succesfuly created!
My progress so far in edit_contact is the following
def edit_contact():
while True:
if question == 'edit':
contact_edit = input('Enter the name of the contact you want to add: ')
join_edit = dir_path + "\\" + contact_edit + ".txt"
if os.path.exists(join_edit):
contact_input_delete = input('Do you want to edit phone number, or email adress? Type number, or email: ').lower()
if contact_input_delete == 'number':
with open(join_edit, 'w') as file:
data = file.readlines()
file.writelines(data)
else:
print("This contact doesn't exists.")
continue
if you want to see my whole function, you can check it on github: Github
Since the file content will always be limited to two lines, you can reuse the whole add_contact() function, with a minor change, in the first open of the file use "w" argument, f = open(join_input, "w"), this will clear whatever is stored previously in the file, the second open should stay "a" to not clear the phone number. And of course you need to do some cosmetic changes (print messages), anyways the new code will be:
def edit_contact():
contact_name = input('Enter the name of the contact you want to add: ')
join_input = dir_path + "\\" + contact_name + ".txt"
os.makedirs(dir_path, exist_ok=True)
if not os.path.exists(join_input):#we need to reverse the condition here, if the contact is found we can edit it, otherwise we need to skip the use's input
print('this contact does not exist')
else:
while True:
contact_number = input("Enter the contact's number: ")
if not contact_number.isdigit():
print('Type a number next time.')
continue
else:
f = open(join_input, "w")
f.write('Phone number: ' + contact_number)
f.write('\n')
f.close()
email_print = input('Would you like to add an email address? Type yes or no: ').lower()
if email_print == 'yes':
contact_email = input("Enter the contact's email: ")
f = open(join_input, "a")
f.write('Email Adress: ')
f.write(contact_email)
f.close()
print('Contact', contact_name, 'is succesfuly created!')
break
elif email_print == 'no':
print('Contact', contact_name, 'is succesfuly created!')
break
else:
continue

Error code when trying to write to a text file

Basically I started Python a couple of days ago and wanted to create a program that could read and write files. Problem is I get this error:
io.UnsupportedOperation: not writable
choice = input("Open / Create file: ")
if choice == 'Create' or choice == 'create':
new_file_name = input("Create a name for the file: ")
print(open(new_file_name, "w"))
text = input("Type to write to file: \n")
file2 = open(new_file_name)
print(file2.write(text))
print("Reading file...")
print(open(new_file_name, "r"))
print(file2.read())
elif choice == 'Open' or choice == 'open':
filename = input("File name or directory: ")
file = open(filename)
open(filename, "r")
time.sleep(1)
print("Reading file...")
time.sleep(1)
print(file.read())
choice2 = input("Write to file? Y/N \n")
if choice2 == 'Y' or choice2 == 'y':
text2 = input("Type to write to file: ")
open(filename, "w")
file = open(filename)
file.write(text2)
choice3 = input("Read file? Y/N ")
if choice3 == 'Y' or choice3 == 'y':
print(file.read())
Your idea of issuing progress reports from your code is a good one, especially in the beginning stages. But it appears that you don't quite understand the difference between
print(open(new_file_name, "w"))
which is what your code actually does, and
print(f'open("{new_file_name}", "w")')
I believe the second of these is what you meant to do: it prints
open("myfile.txt", "w")
but what your actual code does is to (1) create an open file object for writing, then (2) print its type and memory location to the screen, and finally (3) throw it away.
So the first fix is to take out the print() calls, or at least reduce them to print("step 1") etc until you know how to do it properly.
The second fix is to not respond to the choice of Create by trying to read the file. If the user is creating the file then they are clearly not interested in the contents of any previous version. Your code responds to Create by reading the file, and that seems back-to-front to me, and in general programs should work the way that the average user, for example me, will think intuitive. Here is a correct way to do the Create bit:
choice = input("Open / Create file: ")
if choice == 'Create' or choice == 'create':
new_file_name = input("Create a name for the file: ")
with open(new_file_name, "w") as file2:
file2.write("This is stuff to go into the created file.\n")
else:
...
This asks for the name of the file, opens it for writing, then writes some stuff to it.

Update single field in text file python

I have this function:
def favourites():
name = input("Enter your name as you did when you signed up: ")
new_artist = input("Would you like to edit your favourite artist? y/n ").lower().strip()
if new_artist == 'yes' or new_artist == 'y':
old_artist = input("Enter the favourite artist you used when signing up: ")
artist = input("Enter your new favourite artist: ")
usersFile = open('users.txt', 'r+')
usersRec = usersFile.readline()
# reads each line in the file
while usersRec != "":
# splits each record into fields
field = usersRec.split(',')
if field[0] == name:
usersFile.write(field[2].replace(old_artist, artist))
usersRec = usersFile.readline()
usersFile.close()
I have read a line in the text file and then split it into fields and i want to update a single field. Searched and found the update() function so tried that but it doesn't work and i'm not sure what i'm doing wrong. Any suggestions?
You should write to file in another stream, opening file for writing. Also made some corrections in readlines() method and 'replace' part (you should put the result into variable which is field[2]):
import io
import sys
def favourites():
content=[]
name = input("Enter your name as you did when you signed up: ")
new_artist = input("Would you like to edit your favourite artist? y/n
").lower().strip()
if new_artist == 'yes' or new_artist == 'y':
old_artist = input("Enter the favourite artist you used when signing
up: ")
artist = input("Enter your new favourite artist: ")
with open('users.txt', 'r+') as usersFile:
usersRec = usersFile.readlines()
print(usersRec)
# reads each line in the file
for ur in usersRec:
# splits each record into fields
field = ur.split(',')
if field[0] == name:
field[2] = field[2].replace(old_artist, artist)
content.append(','.join(field))
else:
content.append(','.join(field))
usersRec = usersFile.readline()
usersFile.close()
writeToFile(content)
def writeToFile(content):
with open('users.txt', 'w+') as usersFile:
for line in content:
usersFile.write(line)
usersFile.close()
if __name__=="__main__":
favourites()

How can you use a while loop so the user can open a new text file? Python

I want to use a while loop that will give the user an opportunity to open a new text file at the end of the program. Here is the code I have:
run_again = "yes"
run_again = run_again.upper().strip()
while run_again == "yes":
open_file = input("Please enter name of file: ")
file_name = open(open_file,"r")
for line in file_name:
line = line.strip()
rows = line.split(" ")
num = rows[0]
print(num)
run_again = input("Would you like to open a new file (yes or no)? ")
if run_again != "yes":
print("Have a great day!")
I've managed to make a while loop work with other code but I can't get it to work with opening text files.
I think something like that would work. Can't really test now.
run_again = True
while run_again:
open_file = input("Please enter name of file: ")
file_name = open(open_file,"r")
for line in file_name:
line = line.strip()
rows = line.split(" ")
num = rows[0]
print(num)
if input("Would you like to open a new file (yes or no)? ") != "yes":
print("Have a great day!")
break
Edit :
As suggested by Blorgbeard :
while True:
open_file = input("Please enter name of file: ")
file_name = open(open_file,"r")
for line in file_name:
line = line.strip()
rows = line.split(" ")
num = rows[0]
print(num)
if input("Would you like to open a new file (yes or no)? ") != "yes":
print("Have a great day!")
break

Categories