简体   繁体   English

在 python 的文本文件中编辑特定行的一部分

[英]Editing part of a specific line in a text file in python

I'm trying to edit a text file.我正在尝试编辑文本文件。 If my text has less than X lines, I want to add X-1 empty lines and then the line I want to add (for example a variable called my_addition).如果我的文本少于 X 行,我想添加 X-1 个空行,然后添加我想要添加的行(例如一个名为 my_addition 的变量)。 If the text has x or more lines, I need to edit them and add my_addition.如果文本有 x 行或更多行,我需要编辑它们并添加 my_addition。 Text for example:以文字为例:

text:text:text: * (X-1 lines)
my_addition:text:text: (line number X)

You could read the file as an array of lines and modify the last line, then write the modified lines back to the file.您可以将文件作为行数组读取并修改最后一行,然后将修改后的行写回文件。

with open("my_file.txt", "r") as f:     # Open the file in read mode
    lines = f.read().splitlines()       # Get lines as an array
    lines[-1] = "Hello" + lines[-1]     # Add your additon to the last line

with open("my_file.txt", "w") as f:     # open the file in write mode
    for line in lines:
        f.write("%s\n" % line)          # write each line to file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM