isolating a chunk of text from a text file in python 3.8

Viewed 69

so, I am working on something in python and I need to take a Buch of text out of a text file. but I just can't seem to find a way to do it. some context, the amount of things to take out might change, but I think I can figure that out by myself. I need to take out from line 23 to 124, or from character 1216 to 7757 at the moment, I really have no idea on how to make it scalable, but I am sure you guys can help with that too. I've already tried to use the .readlines() & the .readline() methods, but they don't give me what I want. of course, if you need more detail ask and it shall be provided.

2 Answers

You can use readlines() function to get all the lines and then only a part of the list
For characters just use read() then delete all the \n and choose from character number n to t.
example below:

lst = [0,1,2,3,4,5]
print(lst[1:5]) #prints indexes 1 to 4 inclusive so [1,2,3,4], it prints a list
a="01234" 
print(a[3:5]) #same logic it will print third and fourth characters so "34", here it prints a string
print(a.replace('3','') # here all '3' will be replaced by nothing so they'l be deleted, use this to get rid of \n

I don't really know what you problem is so here is a solution:

 with open("yourfile.txt") as file:
    content = file.readlines()

    del content[2:4] # delete third and fourth line

    print(content)
Related