Jeff - Mci
Jeff - Mci

Reputation: 1013

readline() only reading the first line

I'm trying to read multiple lines in a file and it doesn't seem to work when I assigned my readline() method to a variable. It keeps printing the first line. It only seems to work when I don't assign it to a variable. Any ideas?

I'm using Python 3.6.2. Here is my code:

# This is it not working ( I omitted the 'gradesfile_path' variable)

gradesfile = open(gradesfile_path,'r')
readgrades = gradesfile.readline()

print(readgrades)
print(readgrades)

# This is working when I don't call the variable

print(gradesfile.readline())
print(gradesfile.readline())
print(gradesfile.readline())

Upvotes: 1

Views: 5097

Answers (4)

Grrammel
Grrammel

Reputation: 1

Actually, you have to replace readline() with readlines(). Readline() returns only the first line whereas readlines() returns all lines of your file.

Upvotes: 0

Talat Parwez
Talat Parwez

Reputation: 129

readline() is suppose to read the whole file as line by line, so I believe you need to keep calling it everytime you need to read a line and If you're not restricted to use readline(), then your objective can be achieved using:

read():- will read the whole file at once

readlines():- will read the whole file and result it into python list

with open('file_name', 'r') as file_obj:
    print file_obj.readlines()

or

with open('file_name', 'r') as file_obj:
    some_var = file_obj.readlines()
    print some_var

or

with open('file_name', 'r') as file_obj:
    print file_obj.read()

or

with open('file_name', 'r') as file_obj:
    some_var = file_obj.read()
    print some_var

Upvotes: 1

wohe1
wohe1

Reputation: 775

When you assign gradesfile.readline() to a variable, you are actually reading one line and storing that line to the variable

Upvotes: 1

heemayl
heemayl

Reputation: 41987

readline() reads a single line -- the next line in the context of the iterator returned by open(). And you are assigning the line read as variable readgrades which will always contain that line.

Perhaps you meant to assign the method to a variable and call that variable instead:

readgrades = gradesfile.readline  ##Note the absence of call

Then you can do:

readgrades()

Upvotes: 1

Related Questions