您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

line_to_replace = 17 #the line we want to remplace
my_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 )
python 2022/1/1 18:26:33 有191人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶