python删除多行文本
时间: 2023-08-08 17:04:43 浏览: 214
要删除多行文本,可以使用以下代码作为参考:
```python
# 打开原始文件并读取内容
with open('data.txt', 'r') as f:
lines = f.readlines()
# 指定要删除的行号
dirtyid = \[3, 6, 9\]
# 创建一个新的列表,将不需要删除的行添加到其中
new_lines = \[\]
for i, line in enumerate(lines):
if i not in dirtyid:
new_lines.append(line)
# 将新的内容写入新的文件
with open('data_new.txt', 'w') as f:
f.writelines(new_lines)
```
这段代码首先打开原始文件并读取所有行的内容。然后,通过指定要删除的行号,创建一个新的列表,并将不需要删除的行添加到其中。最后,将新的内容写入一个新的文件中。请注意,你需要将`data.txt`替换为你的原始文件名,将`data_new.txt`替换为你想要保存新内容的文件名。
#### 引用[.reference_title]
- *1* [Python,批量删除txt文本指定行](https://blog.csdn.net/qq_37009634/article/details/120761112)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [【python】 根据外部索引删除txt文本多行数据](https://blog.csdn.net/susanhc/article/details/89283810)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [在Python中将多行字符串作为命令行输入(Taking multiple lines of strings as command line input in ...](https://blog.csdn.net/weixin_39839968/article/details/110162181)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文