jorrede
jorrede

Reputation: 17

reading individual line in a file with python

How is this wrong? It seems like I am doing this right but every time. I have tried changing the readline part to read but that didn't work.

Here is my code:

f = open("pg1062.txt","r").read()
print f.readline(1)
print f.readline(2)
print f.readline(3)

Here is the error I get:

 print f.readline(1)
AttributeError: 'str' object has no attribute 'readline'

Upvotes: 0

Views: 54

Answers (3)

Saleem
Saleem

Reputation: 8978

Your problem is at this line

f = open("pg1062.txt","r").read()

just remove .read() and your problem will be fixed. Your final code should look like.

f = open("pg1062.txt","r")
print f.readline()
print f.readline()
print f.readline()

And if you want to print all lines from text file, see code below

f = open("pg1062.txt","r")
for line in f:
    print line

Upvotes: 1

Goodies
Goodies

Reputation: 4681

This is certainly a duplicate. At any rate, anything above Python 2.4 should use a with block.

with open("pg1062.txt", "r") as fin:
    for line in fin:
        print(line)

If you happen to want them in a list:

with open("pg1062.txt", "r") as fin:
    lines = [line for line in fin] # keeps newlines at the end
    lines = [line.rstrip() for line in fin] # deletes the newlines

or more or less equivalently

with open("pg1062.txt", "r") as fin:
    lines = fin.readlines() # keeps newlines at the end
    lines = fin.read().splitlines() # deletes the newlines

Upvotes: 0

TimRin
TimRin

Reputation: 77

This uses a loop to print your lines.

f = open("pg1062.txt", 'r')
while True:
    line = f.readline()
    if line == "":
        break
    print(line)

If you want to only print a specific number of lines, then do something like this:

f = open("pg1062.txt", 'r')
count = 1
while count < 4:
    line = f.readline()
    if line == "":
        break
    print(line)
    count += 1

Upvotes: 1

Related Questions