can I please get help with this Python program?
I want to learn Python so I started writing my first program which is a phone book directory. It has the options to add a name and phone number, remove numbers, and search for them.
Basically, my program stores the numbers to a list in a file. I cannot figure out how to remove a particular line in the file but keep the rest of the file intact. Can someone please help me with this?
Oh, darkmistry is right.
markupif line.strip() == coname.strip():
wil not find the line, since the line will also contain the number.
His suggested markupif coname in line:
could return some false matches, but something like this should work(assuming no spaces in phone number):
if name == coname:
My other points still stand.
I played with it today and I got this working…
coname = raw_input('What company do you want to remove? ') # company name
f = open('codilist.txt')
tmpfile = open('codilist.tmp', 'w')
for line in f:
if coname in line:
print coname + ' has been removed.'
else:
tmpfile.write(line)
f.close()
tmpfile.close()
os.rename('codilist.tmp', 'codilist.txt')
continue```
prox wrote: so what does line.rsplit(' ', 1) do exactly?
Help on built-in function rsplit:
rsplit(…) S.rsplit([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string S, using sep as the
delimiter string, starting at the end of the string and working
to the front. If maxsplit is given, at most maxsplit splits are
done. If sep is not specified or is None, any whitespace string
is a separator.
>>> name, number = text.rsplit(' ', 1)
>>> name
'test'
>>> number
'123'
>>>
Try things before asking, prox.