0

I still cant figured out how to slicing a 'string' and then grab the whole line after finding some 'string'. this is what i do so far :

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

my script:

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])

output 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

the output that i need is :

#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

thanks before, i hope my explanation was clearly Any help would be greatly appreciated!

1 Answers1

0

You could do :

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)
iFlo
  • 1,442
  • 10
  • 19
  • Thankyou its really help me out ! if you willing to explain me more, what these ("%s\n" % line) script mean ? – alanyukeroo Jan 20 '17 at 17:10
  • That means that you write a new line from the original fine. The part "%s" is where your string will be. And you replace this string by "% line" which mean that "%s" takes the value of "line". "\n" is here to add a new line in your file. – iFlo Jan 23 '17 at 07:51