【问题标题】:Python - how do I remove last two lines of file, append lines, then replace those two lines I removed? [duplicate]Python - 如何删除文件的最后两行,追加行,然后替换我删除的那两行? [复制]
【发布时间】:2018-01-11 20:21:01
【问题描述】:

我正在使用 Flask 进行开发,并且正在尝试创建一个页面来创建页面(作为一种自定义 CMS)。因此,页面需要为在 app.py 文件中调用时呈现页面模板的函数创建自己的 @app.route 装饰器。我想出的是创建三个函数:remove_last_two_linescreate_rendering_funcadd_back_last_lines(以他们的工作命名)。 remove_last_two_lines 函数和 add_back_last_lines 函数正是我想要的。我遇到的问题是create_rendering_func。它根本不做任何事情,也不会引发错误。所以我认为代码是有效的(并且我传递了有效的参数),我只是不明白为什么它不起作用。被覆盖的行是空的(这就是为什么在函数的最后一行之后有多个换行符)。提前致谢!

def add_new_url(route, func_name, title, filename):
    lines = open(__file__, 'r').readlines()
    lines[-6] = '@app.route(\'%s\')' % route
    lines[-5] = '\ndef %s' % func_name
    lines[-4] = '\n\trender_template(\'filename\', the_title=%s)\n\n\n\n\n' % title 

(这种方法很烂。任何关于更好方法的提示表示赞赏)

【问题讨论】:

    标签: python flask


    【解决方案1】:

    我会将要插入的数据写成一个由换行符 (\n) 附加的字符串列表,然后通过切片将其插入lines

    insert_lines = ["Hello\n", "World!\n"]
    with open("my_text_file.txt") as myfile:
        lines = myfile.readlines()
        lines[-2:-2] = insert_lines
        myfile.seek(0)
        myfile.write(''.join(lines))
    

    它需要将整个文件读入内存并在写入之前在内存中创建一个新文件,如果您的文件非常大,这可能会出现问题,但它会插入“Hello”和“World!”在文件的倒数第二行之前。

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 1970-01-01
      • 2018-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-06
      • 2017-05-20
      相关资源
      最近更新 更多