with open("data.txt", "r") as infile:
x = infile.readlines()
x = [i.strip() for i in x[x.index('UniqueString\n') + 1:] if i != '\n' ]
with open("output.txt", "w") as outfile:
for i in x[1:]:
outfile.write(i+"\n")
def extract_lines_following(file, marker=None):
"""Generator yielding all lines in file following the line following the marker.
"""
marker_seen = False
while True:
line = file.next()
if marker_seen:
yield line
elif line.strip() == marker:
marker_seen = True
file.next() # skip following line, too
# sample usage
with open('test_data.txt', 'r') as infile, open('cleaned_data.txt', 'w') as outfile:
outfile.writelines(extract_lines_following(infile, 'UniqueString'))
您可以提取数据并将其写入另一个文件,如下所示:
我认为这很简单:文件被打开,所有的行都被读取,一个列表从头字符串开始,剩下的行被再次写入文件。你知道吗
这是你要找的吗?你知道吗
工作原理:
[... for line in infile]
逐行读取infile
False
,则writeline()
不会被触发。你知道吗or
部分中,如果找到所需的行,我们将设置触发器,因此writeline
将为下一行和后续行触发False
您可以创建一个generator function(以及更多信息here),为您过滤文件。
它以增量方式运行,因此不需要一次将整个文件读入内存。你知道吗
如果您使用的是python3,则可以对其进行一些优化,但基本思想是相同的。你知道吗
相关问题 更多 >
编程相关推荐