Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.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 - Fatal编程技术网

Python 隔离并处理文本文件中的某些行

Python 隔离并处理文本文件中的某些行,python,Python,我正在使用python。我有一个文本文件,其格式如下: ########### text lines ########### text lines ########### text lines ########### 我想为两条“########”线之间找到的每个线段运行一个算法。 如何引用两行“#######”之间的文本行。 两条“#######”行之间的行数不是固定的 谢谢这行吗 f = open("textfile.txt") for line in f.readlines():

我正在使用python。我有一个文本文件,其格式如下:

###########
text lines
###########
text lines
###########
text lines
###########
我想为两条“########”线之间找到的每个线段运行一个算法。 如何引用两行“#######”之间的文本行。 两条“#######”行之间的行数不是固定的

谢谢这行吗

f = open("textfile.txt")
for line in f.readlines():
   if '######' not in line:
       print(line) # evaluate and process the line here

使用
split()
,您可以很容易地做到这一点:

或者这个怎么样:

with open("f.txt") as f:
    print(''.join(x for x in filter(lambda x: x != '###########', f.read().split("\n"))))
file.txt

###########
line1
#
line2
######
line3
line4
line5
##########
line6
line7
代码:

考虑到“\n”不包含“\n”:

其他:


你所说的“参考”是什么意思?在遍历文件中的所有行时简单地计算它们的值,忽略######?除了重新分配上下文管理器之外,这个答案看起来不错。
###########
line1
#
line2
######
line3
line4
line5
##########
line6
line7
import re

FILE_PATH = "file.txt"

blocks = []
lines = []

with open(FILE_PATH) as file:
    for line in file:
        if re.fullmatch(r"#+(\n){0,1}", line):
            if lines:
                blocks.append(lines)
                lines = []
        else:
            lines.append(line.rstrip("\n"))  # remove rstrip if you want to keep a new line at the end of a line

# store last block (if file does not end with #+ line)
if lines:
    blocks.append(lines)

print(blocks)  # [['line1'], ['line2'], ['line3', 'line4', 'line5'], ['line6', 'line7']]
def get_chunks(filename):
    with open(filename) as f:
        return f.read().split('#'*6)[2:-1:2]
import re

def get_chunks(filename):
    with open(filename) as f:
        return re.split(r'(#\n?){6}', f.read())[4:-1:4]