![](/img/trans.png)
[英]How to read specific characters from lines in a text file using python?
[英]python - Read file from and to specific lines of text
我不是在谈论特定的行号,因为我正在阅读具有相同格式但长度不同的多个文件。
说我有这个文本文件:
Something here...
... ... ...
Start #I want this block of text
a b c d e f g
h i j k l m n
End #until this line of the file
something here...
... ... ...
我希望你知道我的意思。 我正在考虑迭代文件,然后使用正则表达式搜索,找到“开始”和“结束”的行号,然后使用linecache从开始行读取到结束行。 但是如何获得行号? 我可以使用什么功能?
如果您只想在Start
和End
之间使用文本块,您可以执行以下简单操作:
with open('test.txt') as input_data:
# Skips text before the beginning of the interesting block:
for line in input_data:
if line.strip() == 'Start': # Or whatever test is needed
break
# Reads text until the end of the block:
for line in input_data: # This keeps reading the file
if line.strip() == 'End':
break
print line # Line is extracted (or block_of_lines.append(line), etc.)
实际上,您不需要操作行号就可以读取开始和结束标记之间的数据。
逻辑(“读取直到......”)在两个块中重复,但它非常清晰和有效(其他方法通常涉及检查某些状态[在块/块内/块到达之前],这会导致时间损失)。
这是有用的东西:
data_file = open("test.txt")
block = ""
found = False
for line in data_file:
if found:
block += line
if line.strip() == "End": break
else:
if line.strip() == "Start":
found = True
block = "Start"
data_file.close()
你可以很容易地使用正则表达式。 你可以根据需要使它更健壮,下面是一个简单的例子。
>>> import re
>>> START = "some"
>>> END = "Hello"
>>> test = "this is some\nsample text\nthat has the\nwords Hello World\n"
>>> m = re.compile(r'%s.*?%s' % (START,END), re.S)
>>> m.search(test).group(0)
'some\nsample text\nthat has the\nwords Hello'
这应该是一个开始:
started = False
collected_lines = []
with open(path, "r") as fp:
for i, line in enumerate(fp.readlines()):
if line.rstrip() == "Start":
started = True
print "started at line", i # counts from zero !
continue
if started and line.rstrip()=="End":
print "end at line", i
break
# process line
collected_lines.append(line.rstrip())
enumerate
生成器使用生成器并枚举迭代。 例如。
print list(enumerate("a b c".split()))
版画
[ (0, "a"), (1,"b"), (2, "c") ]
更新 :
海报要求使用正则表达式来匹配“===”和“======”之类的行:
import re
print re.match("^=+$", "===") is not None
print re.match("^=+$", "======") is not None
print re.match("^=+$", "=") is not None
print re.match("^=+$", "=abc") is not None
print re.match("^=+$", "abc=") is not None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.