目标:
要删除文件的特定部分(从Lower_range到upper_range)
到目前为止,我已经设法从文件中选择要删除的部分。
fh = open("sample.txt", "r")
lower_range, upper_range = [int(x) for x in raw_input("enter both ranges").split(',')]
lines = fh.readlines()
i = 0
for line in lines:
if (upper_range >= i) and (lower_range <= i):
print(lines[i])
i += 1
else:
i += 1
fh.close()
sample.txt
The possibility of losing helium forever poses
the threat of a real crisis because its unique
qualities are extraordinarily difficult, if not
impossible to duplicate (certainly, no biosynthetic
ersatz product is close to approaching the point of
feasibility for helium, even as similar developments
continue apace for oil and coal).Helium is even cheerfully
derided as a “loner” element since it does not adhere
to other molecules like its cousin, hydrogen.According
to Dr. Lee Sobotka, helium is the “most noble of gases,
meaning it’s very stable and non-reactive for the most
part … it has a closed electronic configuration, a very
tightly bound atom.It is this coveting of its own electrons
that prevents combination with other elements’.Another
important attribute is helium’s unique boiling point,
which is lower than that for any other element.
如果lower_range = 1&upper_range = 5
输出
the threat of a real crisis because its unique
qualities are extraordinarily difficult, if not
impossible to duplicate (certainly, no biosynthetic
ersatz product is close to approaching the point of
feasibility for helium, even as similar developments
相当懒惰手动删除行,所以有什么想法怎么做?先谢谢您的帮助。
答案 0 :(得分:0)
您的解决方案将文件读入内存,这是次优的。
您可以使用enumerate()
在行号和行之间进行循环,并使用条件的复合比较(x < y < z
)。您可能希望将<=
调整为<
。
我们还使用yield
定义了可以迭代的生成器函数。
def filter_lines(filename, start_line, end_line):
with open(filename) as f:
for i, line in enumerate(f):
if start_line <= i <= end_line:
yield line
for line in filter_lines('sample.txt', 1, 5):
print(line)
编辑:如果要将新行写入新文件,只需:
with open('sample2.txt', 'w') as f:
for line in filter_lines('sample.txt', 1, 5):
print(line, file=f)