我有一个文件,如下:
the 1 file is:
none
the 2 file is:
a-h-f
the 3 file is:
a-h-p
the 4 file is:
none
我想使用python知道哪两个连续文件是争用的,而不是无。以此文件为例," 2文件"和" 3档"是持续的,有内容。我期待的结果是:
the 2 file is:
a-h-f
the 3 file is:
a-h-p
请有人给我一些提示。谢谢。
答案 0 :(得分:1)
将您的行放在列表中,即lines = f.readlines()
f
是文件对象,或者:
lines = '''the 1 file is:
none
the 2 file is:
a-h-f
the 3 file is:
a-h-p
the 4 file is:
none
'''.splitlines()
然后:
for t in zip(*[lines[i::2] for i in range(4)]):
if 'none' not in t:
# t is ('the 2 file is:', 'a-h-f', 'the 3 file is:', 'a-h-p')
# do something with it, e.g.:
for x in t:
print(x)
打印:
the 2 file is:
a-h-f
the 3 file is:
a-h-p
答案 1 :(得分:0)
列出4个连续元素并过滤掉没有元素的元素。派对......
with open("input_file","r") as in_file:
lines = in_file.read().split("\n")
consecutive_lines_4 = [lines[i:i+4] for i in range(0,len(lines)-3),2]
result = [i for i in consecutive_lines_4 if 'none' not in i]
print(result)