Python更改txt文件一行内容
时间: 2023-08-14 20:33:25 浏览: 52
要更改txt文件中的一行内容,可以先读取整个文件内容,然后对需要更改的行进行修改,最后将修改后的内容覆盖原文件。具体步骤如下:
1. 打开要更改的txt文件,可以使用open函数,指定文件名和打开模式,例如:
```
file = open("example.txt", "r")
```
其中,"r"表示只读模式。
2. 读取整个文件内容,可以使用readlines函数,例如:
```
lines = file.readlines()
```
3. 定位要更改的行,可以通过索引或循环查找,例如:
```
index = 1 # 要更改的行号
lines[index] = "new content\n" # 将要更改的行替换为新内容,注意要加上换行符
```
4. 关闭文件,可以使用close函数,例如:
```
file.close()
```
5. 将修改后的内容覆盖原文件,可以使用open函数以写模式打开文件,然后使用writelines函数写入新内容,例如:
```
file = open("example.txt", "w")
file.writelines(lines)
file.close()
```
完整的例子如下:
```
file = open("example.txt", "r")
lines = file.readlines()
index = 1 # 要更改的行号
lines[index] = "new content\n" # 将要更改的行替换为新内容,注意要加上换行符
file.close()
file = open("example.txt", "w")
file.writelines(lines)
file.close()
```
注意:在修改文本文件时,要注意原文件的编码格式,以免出现乱码。