t work 尝试删除文件中的最后一个字符但工作不成功

2024-05-16 09:23:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码,它可以将一些东西写入一个文件中,这个文件工作得很好,但是在我可以将它用于其他东西之前,我需要删除文件中最后一个字符。你知道吗

我当前的代码如下所示

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) 

需要编辑的文件如下所示

"/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",

我需要删除文件的最后一个字符,在这个例子中是逗号,但我似乎无法使它工作。你知道吗


Tags: 文件django代码homeadminvarlibmedia
2条回答

试试这个代码。你知道吗

# 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()

我可能误解了这个问题,但我想你可能是自己在写逗号?你知道吗

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

                                      ^
                                      | there

你就不能把它取下来吗?你知道吗

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

相关问题 更多 >