我仍然无法弄清楚如何切割字符串'找到一些'字符串'然后抓住整行。 这是我到目前为止所做的:
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])
输出result.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
谢谢,我希望我的解释清楚
任何帮助将不胜感激!
答案 0 :(得分:0)
你可以这样做:
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)