Lesnie Sncheider
Lesnie Sncheider

Reputation: 375

Trying to remove last character in file but doesn't work

I have this code which writes some stuff into a file which works perfectly, but before I can use this for something else I need to remove the very last character in the file.

My current code looks like this

for root, dirs, files in os.walk(cwd):
            for file in files:
                if file.endswith('.blend'):
                    with open("filepaths","a+") as f:
                        f.write(f'"{os.path.join(root, file)}",\n')
with open("filepaths", 'rb+') as f:
    f.seek(0,2)
    size=f.tell()
    f.truncate(size-1) 

The file that needs to be edited looks like this

"/home/django/copypaste/cleanup/var/media/admin/cedd0c01-930e-4b43-91de-c45447a8f30f/splash279/splash279.blend",
"/home/django/copypaste/cleanup/var/media/admin/cedd0c01-930e-4b43-91de-c45447a8f30f/splash279/lib/props/barbershop_pole.blend",
"/home/django/copypaste/cleanup/var/media/admin/cedd0c01-930e-4b43-91de-c45447a8f30f/splash279/lib/props/hairdryer.blend",
"/home/django/copypaste/cleanup/var/media/admin/cedd0c01-930e-4b43-91de-c45447a8f30f/splash279/lib/chars/pigeon.blend",
"/home/django/copypaste/cleanup/var/media/admin/cedd0c01-930e-4b43-91de-c45447a8f30f/splash279/lib/chars/agent.blend",
"/home/django/copypaste/cleanup/var/media/admin/cedd0c01-930e-4b43-91de-c45447a8f30f/splash279/lib/nodes/nodes_shaders.blend",
"/home/django/copypaste/cleanup/var/media/admin/cedd0c01-930e-4b43-91de-c45447a8f30f/splash279/tools/camera_rig.blend",

I'm in need of removing the very last character of the file which in this case in the comma, but I can't seem to make it work.

Upvotes: 1

Views: 95

Answers (2)

finefoot
finefoot

Reputation: 11232

It's possible that I misunderstand the question but I think you might be writing the comma yourself?

f.write(f'"{os.path.join(root, file)}",\n')

                                      ^
                                      | there

Can't you just remove it?

f.write(f'"{os.path.join(root, file)}"\n')

Upvotes: 0

CodeIt
CodeIt

Reputation: 3618

Try this code.

# Use file.seek() to seek 1 position from the end, then use file.truncate() to remove the remainder of the file.

with open("a.blend", 'rb+') as filehandle:
    filehandle.seek(-1, os.SEEK_END)
    filehandle.truncate()

Upvotes: 1

Related Questions