Reputation: 33
Basically I want to remove a line in my bank.txt
file which has names, account numbers and a balance in it.
So far I have how to setup the file and how to check that the information is in the file I'm just not sure as to how I'm going to remove the certain line if the information is the same as what the input looks for.
Any help is appreciated and sorry if I've gotten either this question or the actual code itself formatted incorrectly for the question, don't really use this site much so far.
Thanks in advance.
filename = "bank.txt"
word1 = str(input("What is your name?"))
with open(filename) as f_obj:
for line in f_obj:
if word1 in line:
print(line.rstrip())
print("True")
else:
print("False")
Upvotes: 3
Views: 118
Reputation: 185
This code works in case you want to delete multiple lines and not just the first. I also sought to approximate your code as much as possible. The user input is treated the same way, the deleted lines are printed and "True" or "False" are printed depending on whether a line was deleted or not.
deleted = False # becomes True if a line is removed
# get lines from file
f = open("bank.txt","r")
lines = f.readlines()
f.close()
# get name from user
word1 = str(input("What is your name? "))
# open for writing
f = open("bank.txt","w")
# reprint all lines but the desired ones
for i in range(len(lines)):
if word1 in lines[i]:
print(lines[i])
deleted = True
else:
f.write(lines[i])
# close file
f.close()
print(str(deleted))
Upvotes: 1
Reputation: 13498
First lets open up your file and load its contents into a list:
with open("bank.txt", 'r') as f:
lines = f.readlines()
Now that we have all the lines stored as a list, you can iterate through them and remove the ones you don't want. For example, lets say that I want to remove all lines with the word 'bank'
new_lines = []
for line in lines:
if 'bank' not in lines:
new_lines.append(line)
new_lines is now a list of all the lines that we actually want. So we can go back and update our file
with open("bank.txt", 'w+') as f:
to_write = ''.join(new_lines) #convert the list into a string we can write
f.write(new_lines)
Now no lines in the text file have the word 'bank'
Upvotes: 2