代码之家  ›  专栏  ›  技术社区  ›  Paties

如何在文本行之间添加空行。txt文件?

  •  0
  • Paties  · 技术社区  · 2 年前

    代码的目的是在文本行之间添加一个空行。txt文档,并在这些空行中写下一些单词。 我试着循环浏览每一行,但文件应该是只读模式;

    iushnaufihsnuesa
    fsuhadnfuisgadnfuigasdf
    asfhasndfusaugdf
    suhdfnciusgenfuigsaueifcas
    

    这是一个文本示例。豺狼末日 我如何在这个txt上实现这一点?

    f = open("text.txt", 'w+')
    for x in f:
    f.write("\n Words between spacing")
    
    f.close()
    

    首先,我试着直接在每一行之间画一条新的线,然后加上两个Stuf

    我还想过先在每一行之间画空行,然后在空白处加上一些单词,但我没有想到这一点

    2 回复  |  直到 2 年前
        1
  •  3
  •   quamrana Ryuzaki L    2 年前

    好的,对于200行长的文件,可以将整个文件存储为字符串列表,并在重新写入文件时添加行:

    with open("text.txt", 'r') as f:
        data = [line for line in f]
    
    with open("text.txt", 'w') as f:
        for line in data:
            f.write(line)
            f.write("Words between spacing\n")
    
        2
  •  1
  •   RrR2010    2 年前

    您可以将此操作分为三个步骤。 list[str] 使用 f.readlines() :

    with open("text.txt", "r") as f: # using "read" mode
        lines = f.readlines()
    

    第二种方法是使用 "".join(...) 作用

    lines = "My line between the lines\n".join(lines)
    

    在第三步中,将其记录到文件中:

    with open("text.txt", "w") as f: # using "write" mode
        f.write(lines)
    

    此外,你可以使用 f.read() 结合 text.replace("\n", ...) :

    with open("text.txt", "r") as f:
        full_text = f.read()
    
    full_text = full_text.replace("\n", "\nMy desirable text between the lines\n")
    
    with open("text.txt", "w") as f:
        f.write(full_text)
    

    初始文本:

    iushnaufihsnuesa
    fsuhadnfuisgadnfuigasdf
    asfhasndfusaugdf
    suhdfnciusgenfuigsaueifcas
    

    最后文本:

    iushnaufihsnuesa
    My desirable text between the lines
    fsuhadnfuisgadnfuigasdf
    My desirable text between the lines
    asfhasndfusaugdf
    My desirable text between the lines
    suhdfnciusgenfuigsaueifcas