Deleting a person from a file not in a list - python

For class I need to put names into a file then have the user type in the name they want to delete, and it deletes them. I almost have it it just deletes 2 people at once and I'm not sure why.
import os
def main():
found=False
search=input("Who would you like to delete? ")
student_grades = open("student_grades.txt", 'r')
temp_file= open('temp.txt', 'w')
descr = student_grades.readline()
while descr != '':
qty = (student_grades.readline())
descr = descr.rstrip('\n')
if descr != search:
temp_file.write(descr + '\n')
temp_file.write(str(qty) + '\n')
else:
found = True
descr = student_grades.readline()
student_grades.close()
temp_file.close()
os.rename('temp.txt', 'grades.txt')
if found:
print('The file has been updated.')
else:
print('That student was not found in the file.')
main()
There is also 2 files. student_grades.txt that has the names in it, and temp.txt with nothing. When typing in the name of the person, it can find them but it deletes 2 people instead of the one that was searched.

If you are using Python3.6+
from pathlib import Path
fname = "student_grades.txt"
def bak_file(old_name, new_name=None):
if new_name is None:
new_name = old_name + '.bak'
Path(new_name).write_bytes(Path(old_name).read_bytes())
print('-->', f'cp {old_name} {new_name}')
def main():
bak_file(fname)
lines = Path(fname).read_text().splitlines()
search = input("Who would you like to delete? ").strip()
if search in lines:
updated_lines = [i for i in lines if i != search]
Path(fname).write_text('\n'.join(updated_lines))
print(f'The file {fname} has been updated.')
else:
print('That student was not found in the file.')
if __name__ == '__main__':
main()

Are you sure it deletes two people? This qty = (student_grades.readline()) ... temp_file.write(str(qty) + '\n') makes me think that you might be adding unwanted new lines (no strip when getting the qty, but adding a new line when rewriting it), which might look like you removed two instead of one?
Eraw got it. It works now. I was following a program from my book and they had a slightly different scenario. I deleted qty = (student_grades.readline()) and temp_file.write(str(qty) + '\n') and this deletes only what needs to be deleted. Thanks!

Related

Why do i only get the first input exported to .txt file and not all inputs?

I have tried multiple ways to do this but I struggle. I am new to Python trying to learn currently.
CustomerList = []
Customers = {}
Dates = {}
while True:
Customer_Name = input("Customer's Name:")
CustomerList.append(Customer_Name)
Customers_Address = input("Customer's Address:")
if Customer_Name in Customers:
Customers[Customer_Name]['Orders'] += 1
Customers[Customer_Name]['TotalAmount'] = Total_Amount
else:
Customers[Customer_Name] = {}
Customers[Customer_Name]['Address'] = Customers_Address
Customers[Customer_Name]['Orders'] = 1
Customers[Customer_Name]['TotalAmount'] = 0
file1 = open('Orders_Per_Users.txt', 'w')
file1.write(Customer_Name + " has ordered " + str(Customers[Customer_Name]['Orders']) + " times in total\n")
file1.close()
This is the output
And this is what I get exported from this output
What I want to .txt export for example is.
John has ordered 1 times in total
Mike has ordered 1 times in total
etc
etc
Opening with a 'w' tag means you are opening the file in write mode. write mode overwrites the previously existing text if any or creates a new file if the file doesnt exist.So what you might wanna do is opening it in 'a' mode (append mode) so that it doesnt overwrite the file but just appends text to it
file1 = open('Orders_Per_Users.txt', 'a')
file1.write(Customer_Name + " has ordered " + str(Customers[Customer_Name]['Orders']) + "
times in total\n")
your file permission should be append
w -
Opens in write-only mode. The pointer is placed at the beginning of
the file and this will overwrite any existing file with the same name.
It will create a new file if one with the same name doesn't exist
a -
Opens a file for appending new information to it. The pointer is
placed at the end of the file. A new file is created if one with the
same name doesn't exist. .
file1 = open('Orders_Per_Users.txt', 'a')
I hope you're enjoying your learning :)
problems are:
your code just update the text each time you add an item because of the mode of write/read operation of the file, you coded it like this:
file1 = open('Orders_Per_Users.txt', 'w')
While the correct mode is 'a' instead of 'w' to append to the file without erasing old written text!
NOTE: even if you correct it to be 'a' another issue will appear! the line will be written again in entering new order!
So what you should do is closing the file file1.close() each time you write to it in the while so your code will be looks like this:
CustomerList = []
Customers = {}
Dates = {}
while True:
Customer_Name = input("Customer's Name:")
CustomerList.append(Customer_Name)
Customers_Address = input("Customer's Address:")
if Customer_Name in Customers:
Customers[Customer_Name]['Orders'] += 1
Customers[Customer_Name]['TotalAmount'] = Total_Amount
else:
Customers[Customer_Name] = {}
Customers[Customer_Name]['Address'] = Customers_Address
Customers[Customer_Name]['Orders'] = 1
Customers[Customer_Name]['TotalAmount'] = 0
file1 = open('Orders_Per_Users.txt', 'a')
file1.write(Customer_Name + " has ordered " + str(Customers[Customer_Name]['Orders']) + " times in total\n")
file1.close()

How To Solve a Index Error Problem With a For Loop

I'm facing a problem where I can't finish my code.
There is a problem where upon running this code it comes up as an IndexError.
name = str(input("Please input the books name that you would like to borrow: ")
file = open("books.txt", "r")
file_contents = []
for line in file:
stripped_line = line.strip()
line_list = stripped_line.split()
file_contents.append(line_list)
file.close()
i = 0
for name in range(len(file_contents)):
i = i +1
if name == file_contents[i]:
table_3= [["Borrow Book","1"],
["Cancel Borrowing","2"]]
headers_3 = ["Details", "No."]
print(tabulate(table_3, headers_3, tablefmt = "grid"))
num = int(input("Please input 1 for confirmation of booking and 2 for canceling the booking: "))
file_contents[i] = changed_name
changed_name = str(changed_name)
if name == file_contents[i]:
IndexError: list index out of range
Example Of The File:
(books.txt)
Exile
Dancing In The Moonlight
Here is your complete solution . I hope it would help You
from tabulate import tabulate
name = str(input("Please input the books name that you would like to borrow: "))
file = open("books.txt", "r")
file_contents = [] #available books
for line in file:
line=line.strip()
file_contents.append(line)
file.close()
print("file content: ",file_contents)
i = 0
if name in file_contents:
table_3= [["Borrow Book","1"],["Cancel Borrowing","2"]]
headers_3 = ["Details", "No."]
print(tabulate(table_3, headers_3, tablefmt = "grid"))
num = int(input("Please input 1 for confirmation of booking and 2 for canceling the booking: "))
if(num==1):
try:
#user wants to withdraw that books so we've to remove that book from our available list of books
file_contents.remove(name)
#now we remove that book name from our available books.txt file
file=open("books.txt","w")
str1=" "
str1.join(file_contents)
file.write(str1)
print("Happy to serve you :-) visit again for more good books")
except Exception as e:
print("There is an error ",e)
else:
print("visit again for more good books")
You're missing with range keyword
Try this
for name in range(len(file_contents)):
#your work
I think you meant to iterate through the file_contents:
# code above elided
file.close()
for line in file_contents:
if name == line:
# following code elided
As the error says, an int cannot be iterable. How can you loop through 4?
The solution? Create a range of numbers:
for name in range(len(file_names)):
It would help if you posted the IndexError that you are getting.
And an example of the file you are opening?
What i think i could discover, is that you are using variable i als iterator, but i cannot find it in your loop.

Combine lines when writing to file in Python?

So I'm trying to write all this info to a .txt file, but due to the names being pulled from a .txt file that goes
Liam
Noah
William
etc...
When I write to a file, it puts the first and last names on separate lines from everything else.
I've looked on StackOverflow for a solution but I couldn't find anything specific enough.
password = input('Enter the Password you would like to use ')
open('names.txt', 'r+')
lines = open("names.txt").readlines()
firstName = lines[0]
words = firstName.split()
firstNameChoice = random.choice(lines)
open('names.txt', 'r+')
lines = open("names.txt").readlines()
lastName = lines[0]
words = lastName.split()
lastNameChoice = random.choice(lines)
def signUp():
randomNumber = str(random.randint(0,10000))
accountFile = open('accounts.txt', 'a')
accountFile.write(firstNameChoice)
accountFile.write(lastNameChoice)
accountFile.write(randomNumber)
accountFile.write('#')
accountFile.write(catchall)
accountFile.write(':')
accountFile.write(password)
accountFile.write('\n')
signUp()
Expectation would be everything printed to one line but that's not the case.
As a quick fix for your problem, you could merge all writing commands in one line:
with open('accounts.txt', 'a') as accountFile: # using a context manager is highly recommended
# with spaces
accountFile.write('{} {} {} # {} : {} \n'.format(
firstNameChoice,
lastNameChoice,
randomNumber,
catchall,
password
)
)
# without spaces
accountFile.write('{}{}{}#{}:{}\n'.format(
firstNameChoice,
lastNameChoice,
randomNumber,
catchall,
password
)
)
If my understanding is right then you want to write everything in one line.
The variables you are writing containing \n while writing into the file.
So you have to replace it with a ' '. Replace this code into your program like:
accountFile.write(firstNameChoice.replace('\n',' '))
accountFile.write(lastNameChoice.replace('\n',' '))
accountFile.write(str(randomNumber).replace('\n',' '))
accountFile.write('#'.replace('\n',' '))
#accountFile.write(catchall)
accountFile.write(':'.replace('\n',' '))
accountFile.write(str(password).replace('\n',' '))
Now it will print like this WilliamWilliam448#:dsada
By the way I dont know what you mean by catchall
The reason it puts it all on a new line is because the strings of your names contains the "\n" on the end because it has an enter to a new line. There is an easy fix for this.
Where you define your first and last name variables add .rstrip() at the end. Like this:
firstNameChoice = random.choice(lines).rstrip()
lastNameChoice = random.choice(lines).rstrip()
def signUp():
randomNumber = str(random.randint(0,10000))
accountFile = open('accounts.txt', 'a')
accountFile.write(f'{firstNameChoice} {lastNameChoice} {randomNumber} # {catchall}: {password} \n')

Python File errors

File = input("Please enter the name for your txt. file: ")
fileName = (File + ".txt")
WRITE = "w"
APPEND = "a"
file = []
name = " "
while name != "DONE" :
name = input("Please enter the guest name (Enter DONE if there is no more names) : ").upper()
fileName.append(name)
fileName.remove("DONE")
print("The guests list in alphabetical order, and it will save in " + fileName + " :")
file.sort()
for U in file :
print(U)
file = open(fileName, mode = WRITE)
file.write(name)
file.close()
print("file written successfully.")
I am just practicing to write the file in Python, but something bad happened.
Here are still some errors about this:
fileName.remove("DONE")
Still showing 'str' error.
filename=filename+name
Use the above code
Python strings are immutable. Therefore you can't use append() on them. Use += instead:
fileName += name
which is shorthand for
fileName = fileName + name
Note how nothing is appended to the string, instead a new one is created and then assigned to fileName.
Try this.
I thought you have some mistaken in variable name.
aFile = input("Please enter the name for your txt. file: ")
fileName = (aFile + ".txt")
WRITE = "w"
APPEND = "a"
file = []
name = " "
while name != "DONE" :
name = input("Please enter the guest name (Enter DONE if there is no more names) : ").upper()
file.append(name)
file.remove("DONE")
print("The guests list in alphabetical order, and it will save in " + fileName + " :")
file.sort()
for U in file :
print(U)
outputfile = open(fileName, mode = WRITE)
outputfile.write(name)
outputfile.close()
print("file written successfully.")
Just right out the bat, you can not append to a toople.
fileName.append(name) #how can you append or remove anything into or from this when it contains toople?
Another thing, I don't know what version of python you are using but, I never seen expression like this
file = open(fileName, mode = WRITE) #this should be something like (file=open(fileName,"w"))
Just overall check your code. Like I said you can not add or remove stuff from a toople; only in lists and dictionaries.
append is the list's method where as fileName declared in your code is treated as string. If your intention is to append the string to file, open the file in "append" mode and write to it:
with open(aFile + ".txt", "a") as f:
f.write("appended text")

Python- Saving Results to a File and Recalling Them

I'm writing a program in Python that will store Student IDs, names, and D.O.B.s.
The program gives the user the ability to remove, add, or find a student. Here is the code:
students={}
def add_student():
#Lastname, Firstname
name=raw_input("Enter Student's Name")
#ID Number
idnum=raw_input("Enter Student's ID Number")
#D.O.B.
bday=raw_input("Enter Student's Date of Birth")
students[idnum]={'name':name, 'bday':bday}
def delete_student():
idnum=raw_input("delete which student:")
del students[idnum]
def find_student():
print "Find"
menu = {}
menu['1']="Add Student."
menu['2']="Delete Student."
menu['3']="Find Student"
menu['4']="Exit"
while True:
options=menu.keys()
options.sort()
for entry in options:
print entry, menu[entry]
selection=raw_input("Please Select:")
if selection =='1':
add_student()
elif selection == '2':
delete_student()
elif selection == '3':
find_students
elif selection == '4':
break
else:
print "Unknown Option Selected!"
The problem I am having is I cannot figure out how to have the program save any added records to a file when the program ends. It also would need to read back the records when the program restarts.
I keep trying to find tutorials for this sort of thing online, but to no avail. Is this the sort of code I'd want to add?:
f = open("myfile.txt", "a")
I'm new to Python so any help would be appreciated. Thanks so much.
It depends, if you want to actually save python objects, check out Pickle or Shelve, but if you just want to output to a text file, then do the following:
with open('nameOfYourSaveFile', 'w') as saveFile:
#.write() does not automatically add a newline, like print does
saveFile.write(myString + "\n")
Here's an answer that explains the different arguments to open, as in w, w+, a, etc.
As an example, say we have:
with open('nameOfYourSaveFile', 'w') as saveFile:
for i in xrange(10):
saveFile.write(name[i] + str(phoneNumber[i]) + email[i] + "\n")
To read the file back, we do:
names = []
numbers = []
emails = []
with open('nameOfYourSaveFile', 'r') as inFile:
for line in inFile:
#get rid of EOL
line = line.rstrip()
#random example
names.append(line[0])
numbers.append(line[1])
emails.append(line[2])
#Or another approach if we want to simply print each token on a newline
for word in line:
print word
import pickle,os
if os.path.exists("database.dat"):
students = pickle.load(open("database.dat"))
else:
students = {}
... #your program
def save():
pickle.dump(students,open("database.dat","w"))

Categories