I have been struggling with this for about two hours, I'm new to python so don't judge!
Essentially, I am trying to read the very last character in a text file, and then detect whether or not it is a comma, "," and if it is, I want to delete that character. I have tried different things, this is what I have now and I am unsure why it does not work.
with open("Student_Directory.txt", "rb ") as filehandle:
filehandle.seek(0, os.SEEK_END)
filehandle.seek(filehandle.tell() - 1, os.SEEK_SET)
last = filehandle.read()
last = str(last)
last = last[2:3]
if last == ",":
with open("Student_Directory.txt", "rb ") as f:
f.seek(-1, os.SEEK_END)
filehandle.truncate()
this reads ValueError: truncate of closed file
I have also tried
with open("Student_Directory.txt", "rb ") as filehandle:
filehandle.seek(0, os.SEEK_END)
filehandle.seek(filehandle.tell() - 1, os.SEEK_SET)
last = filehandle.read()
last = str(last)
last = last[2:3]
if last == ",":
filehandle.truncate()
with this, literally nothing happens. if I remove the if statement, it will truncate the last character just fine, but for some reason I am unable to use the filehandle.read() to generate an if statement of any kind that will actually execute.
CodePudding user response:
You can change just this line filehandle.truncate()
to f.truncate()
. Because filehandle closed when your code exit from with statement. You can't reach out of with scope to filehandle variable.
import os
with open("Student_Directory.txt", "rb ") as filehandle:
filehandle.seek(0, os.SEEK_END)
filehandle.seek(filehandle.tell() - 1, os.SEEK_SET)
last = filehandle.read()
last = str(last)
last = last[2:3]
if last == ",":
with open("Student_Directory.txt", "rb ") as f:
f.seek(-1, os.SEEK_END)
f.truncate()
or
You can remove last character with adding seek() function into your second code as below.
import os
with open("Student_Directory.txt", "rb ") as filehandle:
filehandle.seek(0, os.SEEK_END)
filehandle.seek(filehandle.tell() - 1, os.SEEK_SET)
last = filehandle.read()
last = str(last)
last = last[2:3]
if last == ",":
# Adding seek function to adjust cursor!
filehandle.seek(-1, os.SEEK_END)
filehandle.truncate()
CodePudding user response:
Not sure what some of the lines are doing, but basically you just need to move to the last char, read it and if it meets the condition, move back to the last char and truncate the file:
import os
filepath = "...."
with open(filepath, "rb ") as file_obj:
file_obj.seek(-1, os.SEEK_END)
char = file_obj.read()
if char == b",":
file_obj.seek(-1, os.SEEK_END)
file_obj.truncate()