python如何写入现有txt文件中的特定行

python如何写入现有txt文件中的特定行,第1张

python如何写入现有txt文件中的特定

您可以读取文件,然后写入某些特定行。

line_to_replace = 17 #the line we want to remplacemy_file = 'myfile.txt'with open(my_file, 'r') as file:    lines = file.readlines()#now we have an array of lines. If we want to edit the line 17...if len(lines) > int(line_to_replace):    lines[line_to_replace] = 'The text you want here'with open(my_file, 'w') as file:    file.writelines( lines )


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5649587.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存