在文件Python中的特定文本行中追加数据

2024-04-19 19:44:16 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这样一个文件:

words
words

3245, 3445,
345634, 345678

我想知道是否可以将数据添加到代码的第4行,因此输出如下:

^{pr2}$

我找到了一个类似的教程:appending a data in a specific line of a text file in Python? 但问题是我不想使用.startswith,因为这些文件都有不同的开头。在

谢谢你的帮助!在


Tags: 文件of数据代码textindataline
1条回答
网友
1楼 · 发布于 2024-04-19 19:44:16

你可以这样做

# define a function so you can re-use it for writing to other specific lines
def writetoendofline(lines, line_no, append_txt):
    lines[line_no] = lines[line_no].replace('\n', '') + append_txt + '\n'

# open the file in read mode to read the current input to memory
with open('./text', 'r') as txtfile:
    lines = txtfile.readlines()

# in your case, write to line number 4 (remember, index is 3 for 4th line)   
writetoendofline(lines, 3, ' 67899')

# write the edited content back to the file
with open('./text', 'w') as txtfile:
    txtfile.writelines(lines)

# close the file
txtfile.close()

相关问题 更多 >