I have issue with my code. I have file names.txt with 5 random names in new lines (Ana, Joseph, Greg, Hope, Tiffany). The content of the file should be displayed to the user. After then user is asked which name should be deleted. When user pick the name, all names from the file names.txt should be written in file names2.txt without the picked name. After all, names2.txt is displayed for user.
names = open('names.txt')
# print(names.read())
names2 = open('names2.txt', 'a')
pick = input('Name to delete: ')
for i in names:
if i.strip('\n') != pick:
names2.write(i)
names.close()
names2.close()
names2 = open('names2.txt')
print(names2.read())
When I use 2nd line not as comment file names2.txt will become empty. Don't know why... But I need 2nd line because user need to know the content of the names.txt.
I have no idea how to avoid that problem. I tried to put the names.close() to the last line. As well to 3rd line - but error occured because closed file can't be used in for loop.