【问题标题】:Trying to remove last character in file but doesn't work试图删除文件中的最后一个字符但不起作用
【发布时间】:2019-05-14 17:08:29
【问题描述】:

我有这段代码可以将一些内容写入一个完美运行的文件,但在我可以将它用于其他内容之前,我需要删除文件中的最后一个字符。

我当前的代码是这样的

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

我需要删除文件的最后一个字符,在这种情况下是逗号,但我似乎无法让它工作。

【问题讨论】:

标签: python


【解决方案1】:

我可能误解了这个问题,但我认为您可能自己写了逗号?

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

                                      ^
                                      | there

你不能删除它吗?

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

【讨论】:

  • @LesnieSncheider 或者您是否已经解决了问题?
【解决方案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()

【讨论】:

  • 经过测试,逗号好像还在。
  • 我在 stackoverflow 中搜索了相同的问题,但没有一个答案对我有用。这就是我在这里问的原因。
猜你喜欢
  • 2017-03-22
  • 2015-01-06
  • 2013-09-22
  • 2021-11-06
  • 2012-01-11
  • 2017-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多