python 修改文件第5行内容
时间: 2023-08-31 20:56:16 浏览: 182
你可以使用以下代码来修改文件的第5行内容:
filename = 'your_file.txt' # 替换为你的文件名
new_content = 'This is the new content for line 5.' # 替换为你想要替换的内容
with open(filename, 'r') as file:
lines = file.readlines()
lines[4] = new_content + '\n' # 注意索引是从0开始,所以第5行的索引是4
with open(filename, 'w') as file:
file.writelines(lines)
在这个示例中,我们首先打开文件并将其读取到一个列表中。然后,我们将第5行(索引为4)的内容替换为新的内容,并将修改后的列表再次写入文件中。记得将your_file.txt
替换为你想要修改的文件名,并将This is the new content for line 5.
替换为你想要替换的内容。
阅读全文
相关推荐



















