Guys I have a text file, and I am trying to get my program to focus on a specific part of the text.
How would I do that?

I tried this to no avail:

f = open("book.txt")
f.readlies()[10:3340]

Recommended Answers

All 5 Replies

'''
#part.txt
This is a test.
I want to take out this part,of the text
'''

f = open('part.txt')
#readlines() return a list,so string slice wont work [start:end]
print f.readlines()
#--> ['This is a test.\n', 'I want to take out this part,of the text']


f = open('part.txt')
#read() return a string and you can use string slice
print f.read()[35:44]
#--> this part

#Join() as you may now convert a list to string
''.join(['This is a test.\n', 'I want to take out this part,of the text'])[35:44]
#--> this part

snippsat what I don't understand are the brackets.

Those numbers

[35:44]

are these the starting and ending lines?
or characters?

Because my numbers

[10:3340]

are the starting and ending lines.
I changed my from readlines() to read() like you said, and I still don't get it to focus on that block of text(lines 10 through 3340)

I got it to work, thanks snippsat you are a lifesaver! :)

Should not be so hard to understand it`s a slice method that work on string.
your string[start:end]

>>> s = 'my car'
>>> s[0]
'm'
>>> #m is first,we cont from zero

>>> #So if we want to take out car,we count [start:end]
>>> start = 3
>>> end = 6
>>> s[start:end]
'car'
>>>
from itertools import islice
f = open('11.txt') # alice in wonderland guttenberg
print ''.join(islice(f, 100, 110))
"""Output:
Presently she began again. 'I wonder if I shall fall right THROUGH the
earth! How funny it'll seem to come out among the people that walk with
their heads downward! The Antipathies, I think--' (she was rather glad
there WAS no one listening, this time, as it didn't sound at all the
right word) '--but I shall have to ask them what the name of the country
is, you know. Please, Ma'am, is this New Zealand or Australia?' (and
she tried to curtsey as she spoke--fancy CURTSEYING as you're falling
through the air! Do you think you could manage it?) 'And what an
ignorant little girl she'll think me for asking! No, it'll never do to
"""
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.