1

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.

Lesnie Sncheider
  • 365
  • 3
  • 16
  • Possible duplicate of [Python - Remove very last character in file](https://stackoverflow.com/questions/18857352/python-remove-very-last-character-in-file) – CodeIt Dec 13 '18 at 13:51

2 Answers2

1

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()
CodeIt
  • 3,492
  • 3
  • 26
  • 37
0

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')
finefoot
  • 9,914
  • 7
  • 59
  • 102