Trying to delete a line from my file in python, and its throwing me this error. I have a student database, I want to delete a student/line that has the corresponding student id. E.g., line = 'SanVin22\tSanji\tVinsmoke\tWellington'
. id is the inputted id.
def DelStudent(self, data):
self = id
with open(data, "r ") as datafile:
for line in datafile:
datum = line.split()
if datum[0] == id:
os.remove(line)
pass
Error is:
os.remove(line)
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'SanVin22\tSanji\tVinsmoke\[email protected]\tWellington\t'
I've tried replacing os.remove(line)
with datafile.write(line)
, as all of the tutorials I've seen online, but that ends up deleting every list in the database.
CodePudding user response:
If the idea is to delete the line with the given id
, then gather up all of the non-matching lines (i.e. those that we want to keep) and then write them back to the original file.
def DelStudent(self, data):
new_lines = []
with open(data, "r ") as datafile:
for line in datafile:
datum = line.split()
if datum[0] != id:
new_lines.append(line)
with open(data, "w") as datafile:
for line in new_lines:
datafile.write(line)