python - 删除两个特定行号之间的所有行
问题描述
我需要根据行号删除与其他行之间的所有行。在这个 file.py 中,我怎样才能删除 2º 和 6º 行之间的所有文件?
文件 :
1
2
3
4
5
6
7
8
9
10
使用此代码,我可以删除特定行的上方和/或下方的所有行。但是我不能
代码 :
with open('file.py', 'r') as fin:
data = fin.read().splitlines(True)
with open('ab.py', 'w') as fout:
fout.writelines(data[2:])
我尝试了第二个代码,我只能删除 1 个特定行(当我尝试删除超过 1 个时,它效果不佳)
del_line1 = 1
with open("file.py","r") as textobj:
list = list(textobj)
del list[del_line1 - 1]
with open("file.py","w") as textobj:
for n in list:
textobj.write(n)
解决方案
这比预期的要容易。
dellist = [3, 4, 7] #numbers of the lines to be deleted
with open('data.txt') as inpf:
with open('out.txt', 'w') as of:
for i, line in enumerate(inpf):
if i+1 not in dellist: #i+1 because i starts from 0
of.write(line)
您读取每一行,如果行号不在禁止行列表中,则将该行写入另一个文件。
因此,假设您的原始输入,上面的代码给出:
1
2
5
6
8
9
10
注意:这里我调用了文件data.txt
,最好.py
只对内部有python代码的文件使用扩展名。
推荐阅读
- r - `dplyr:::bind_rows_` 有什么作用?
- elixir - Elixir Phoenix Plugs 及其放置位置
- mongodb - MongoDB:对 UTF-8 字符串进行排序
- javascript - Javascript - 创建和填充包含子数组的关联数组
- json - JSON VB.Net 的类
- itext - iText PdfSmartCopy 正在创建重复字体
- elasticsearch - 无法索引/发现 Elassandra 中的多个字段
- javascript - JQuery Datatable 标头与 tbody 不对齐?
- statistics - ANOVA 结果不一致(AIC VS 偏差)
- java - Apache nifi 无法启动