Python 通过抓取一条线,将线的起点切割到线的终点

Python 通过抓取一条线,将线的起点切割到线的终点,python,regex,slice,Python,Regex,Slice,我仍然不知道如何切割一条“线”,然后在找到一些“线”后抓住整条线。 这就是我目前所做的: content.txt : #Try to grab this line start #Try to grab this line 1 #Try to grab this line 2 #Try to grab this line 3 #Try to grab this line 4 #Try to grab this line 5 #Try to grab this line 6 #Try to grab

我仍然不知道如何切割一条“线”,然后在找到一些“线”后抓住整条线。 这就是我目前所做的:

content.txt :
#Try to grab this line start
#Try to grab this line 1
#Try to grab this line 2
#Try to grab this line 3
#Try to grab this line 4
#Try to grab this line 5
#Try to grab this line 6
#Try to grab this line end
#Try to grab this line 7
#Try to grab this line 8
我的剧本:

f_name = open('D:\PROJECT\Python\content.txt', "r").read()
start = f_name.find('start')
end = f_name.find('end')
jos = slice(start, end)
make = open('D:\PROJECT\Python\result.txt', "w")
make.write(f_name[jos])
输出结果.txt:

    start
    #Try to grab this line 1
    #Try to grab this line 2
    #Try to grab this line 3
    #Try to grab this line 4
    #Try to grab this line 5
    #Try to grab this line 6
    #Try to grab this line
我需要的输出是:

#Try to grab this line start
#Try to grab this line 1
#Try to grab this line 2
#Try to grab this line 3
#Try to grab this line 4
#Try to grab this line 5
#Try to grab this line 6
#Try to grab this line end
谢谢,我希望我的解释清楚 任何帮助都将不胜感激

你可以做:

with open(fname) as f:
    content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content] 
# Get the id of the line with "start"
start_id = [id for id in range(len(content)) if "start" in content[id]][0]
# Get the id of the line with "end"
stop_id = [id for id in range(len(content)) if "end" in content[id]][0]
# Slice our content
sliced = content[start_id : stop_id+1]
# And finally, to get your output : 
for line in sliced : 
    print line
# Or to a file :
make = open('D:\PROJECT\Python\result.txt', "w")
for line in sliced :
    make.write("%s\n" % line)

换句话说,您想知道如何捕获起始分隔符和结束分隔符之间的所有行,包括吗?是的,与整个行相关:,谢谢,它真的帮助了我!如果您愿意向我解释更多,这些(“%s\n”%line)脚本是什么意思?这意味着您要从原来的fine中写一行新行。“%s”部分是字符串所在的位置。将该字符串替换为“%line”,这意味着“%s”取“line”的值。“\n”用于在文件中添加新行。