Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何删除文件的特定部分_Python_Python 3.x_Python 2.7 - Fatal编程技术网

Python 如何删除文件的特定部分

Python 如何删除文件的特定部分,python,python-3.x,python-2.7,Python,Python 3.x,Python 2.7,目标: 删除文件的特定部分(从下\u范围到上\u范围) 到目前为止,我已经设法从文件中选择了我要删除的部分 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 (l

目标:

删除文件的特定部分(从下\u范围到上\u范围)

到目前为止,我已经设法从文件中选择了我要删除的部分

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()
如果下限=1,上限=5

输出

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.
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

手动删除行非常懒,所以有什么办法吗?提前谢谢你的帮助

您的解决方案将文件读入内存,这是次优的

您可以使用
enumerate()
将行号与行一起循环,并对条件进行复合比较(
x
)。您可能希望调整