我有这段代码可以将某些内容写入一个可以正常工作的文件中,但是在将其用于其他用途之前,我需要删除文件中的最后一个字符。
我当前的代码如下
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",
我需要删除文件的最后一个字符(在本例中为逗号),但是我似乎无法使其正常工作。
答案 0 :(得分:1)
尝试此代码。
# 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()
答案 1 :(得分:0)
我可能误解了这个问题,但我认为您可能自己写了逗号?
$context = $this->router->getContext();
$context->setHost($this->container->getParameter('router_host'));
$context->setScheme($this->container->getParameter('router_scheme'));
您不能只删除它吗?
f.write(f'"{os.path.join(root, file)}",\n')
^
| there