怎么删除文件中含有某个字符串的那一行
时间: 2023-05-13 08:06:29 浏览: 134
你可以使用 Python 编写一个脚本来实现这个功能,具体步骤如下:
1. 打开文件,读取每一行内容。
2. 判断每一行是否包含指定的字符串,如果包含,则跳过该行。
3. 如果不包含,则将该行内容写入一个新的文件中。
4. 关闭文件,删除原文件,将新文件重命名为原文件名。
以下是一个示例代码:
```python
import os
def delete_lines_with_string(file_path, string):
# 打开文件,读取每一行内容
with open(file_path, 'r') as f:
lines = f.readlines()
# 写入新文件
with open(file_path + '.new', 'w') as f:
for line in lines:
if string in line:
continue
f.write(line)
# 关闭文件,删除原文件,将新文件重命名为原文件名
os.remove(file_path)
os.rename(file_path + '.new', file_path)
# 示例用法
delete_lines_with_string('test.txt', 'hello')
```
这个函数会删除文件 `test.txt` 中包含字符串 `hello` 的行。你可以将 `file_path` 和 `string` 参数替换为你需要的文件路径和字符串。