1
votes

If I have a text file and I want to read the 1st, 2nd, 3rd, 4th, 5th, 6th, 7th and 8th characters on the second line, what would I write? I'm quite new to python and am using v3.3

Example text file

Hello, my name
is Bob. How are
you?

How would I read just the characters H, E, L, L, (,), ( ), M, and Y?

4
Those characters are from the first line..Martijn Pieters

4 Answers

2
votes

It's not hard:

with open('filename.txt', 'r') as handle:
    first_line = handle.readline()

    print(first_line[0], first_line[1], ...)

You should start by reading through a Python tutorial.

0
votes

Generally speaking:

  1. Open the file
  2. Read it line by line
  3. If the line you are reading is the 2nd one, then:
    1. Read the line character by character
    2. If the character is the 1st, 2nd, 3rd.... print it.

The python specifics of this are really easy. I suggest you see what you can come up with - you'll learn better that way.

0
votes

I would do like this:

with open('thefile.txt') as thefile:
    lines = thefile.readlines()  # return a list with all the lines of the file

# then to print 4th character of 6th line you do (mind zero-based indexing):
print(lines[5][3])

It won't work fine with very large files

-1
votes
# `f` is your file
skip = 1 # in this case we want to skip one line to read characters from the second one
for i in range(skip): # this loop will skip a number of lines
    f.realine()
line = f.readline() # read the line we were looking for
chars = list(line[:8]) # getting first eight characters as a list