Editor

Add a Name Only Once

#588 · File handling · Intermediate · 65 XP · about 12 min

A club keeps its members in a text file, one name per line. Write add_member(filename, name) that adds name at the end of the file on a line of its own, unless the file already lists that member. Return True when the name was added and False when it was already there.

  • Compare names ignoring upper and lower case and any spaces around them, so ' ben' is already there if the file has Ben.
  • Write the new name with the spaces around it removed.
  • The file might not exist yet. Then create it with the name as its first line.
  • The last line of the file might not end with a newline. The new name must still go on a new line.
  • Every line you write ends with a newline.

Examples

If club.txt holds Asha and Ben on two lines:

add_member('club.txt', 'Cara')  # returns True: the file now lists Asha, Ben, Cara
add_member('club.txt', 'ben')   # returns False: Ben is already a member

Constraints

  • Names are never empty, and a name never contains a newline.
  • The file holds at most 10,000 names.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.