[英]Different ways to print a section of a file
我了解python的基础知识,现在我希望通过python编写更多代码。
因此,如果我有一个文本文件,请这样说:
This is the start
Text1
Text2
Text3
This is the end
我想要一个脚本,该脚本将遍历文件,并且仅拉出:
Text1
Text2
Text3
所以我有这种方法:
import sys
string = " "
found = False
with open(sys.argv[1]) as input_file:
for line in input_file:
if "Text" in line:
found = True
if found:
string += line
if "Text3" in line:
break
print "\n".join(string.split()) ## I do this to get rid of the line that's just a new line
我想知道是否可以通过itertools以某种方式在Python上做同样的事情?
我正在尝试以下方法:
with open(sys.argv[1]) as input_file:
for line in iter(input_file.readline,'This is the end\n'):
print line.strip()
但这只是打印空白。 我想知道是否有一种比我的方法更简单/更整洁的方式在两行文本之间打印?
谢谢
found
是多余的。
累积连接时,请使用列表而不是字符串。
由于仅添加了包含Text的行,因此无需过滤掉空行,但是删除其行尾很有用。
如果行必须以Text
开头,而不是仅出现在Text
任何位置,则使用if line.startswith("Text"):
而不是if "Text" in line:
。
考虑:
import sys
L = []
with open(sys.argv[1]) as input_file:
for line in input_file:
if "Text" in line:
L.append(line.strip())
if "Text3" in line:
break
print "\n".join(L)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.