'Python - Simplest method of stripping the last byte from a file?
I want to make a script that will take a file, strip off the last byte of a file. The file can be anything, not just text.
I have been playing around with the seek() and tell() methods, but I can't find a way of dealing with the file that allows me to do this.
I figured it should be relatively trivial, but perhaps Python is not an appropriate tool for this?
fileStripped = file[:-4]
newpath = path + "\\" + fileStripped
if not os.path.exists(newpath):
os.makedirs(newpath)
with open(fname, "r") as f:
f.seek (0, 2) # Seek @ EOF
fsize = f.tell() # Get Size
f=f.read
f=f[:fsize-2]
This method errors, and tells me I can not subscript the f=f[:fsize-2] line
Solution 1:[1]
Seek one byte from the end, and truncate.
f = open(..., 'r+')
f.seek(-1, os.SEEK_END)
f.truncate()
f.close()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ignacio Vazquez-Abrams |
