用 Python 在文件中间插入一行? [英] Insert line at middle of file with Python?

查看:78
本文介绍了用 Python 在文件中间插入一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法做到这一点?假设我有一个文件,它是一个名称列表,如下所示:

Is there a way to do this? Say I have a file that's a list of names that goes like this:

  1. 阿尔弗雷德
  2. 账单
  3. 唐纳德

如何在第 x 行(在本例中为第 3 行)插入第三个名字查理",并自动将所有其他人发送到一行?我见过其他类似的问题,但他们没有得到有用的答案.是否可以完成,最好使用方法或循环?

How could I insert the third name, "Charlie", at line x (in this case 3), and automatically send all others down one line? I've seen other questions like this, but they didn't get helpful answers. Can it be done, preferably with either a method or a loop?

推荐答案

这是一种解决问题的方法.

This is a way of doing the trick.

with open("path_to_file", "r") as f:
    contents = f.readlines()

contents.insert(index, value)

with open("path_to_file", "w") as f:
    contents = "".join(contents)
    f.write(contents)

indexvalue 是您选择的行和值,行从 0 开始.

index and value are the line and value of your choice, lines starting from 0.

这篇关于用 Python 在文件中间插入一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆