Python Forum
read file assistance - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: read file assistance (/thread-7247.html)



read file assistance - flatman123 - Dec-30-2017

Hello

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?

heres my code:
# i'm using Python 3.6.2

# Here is it not working
gradesfile = open(gradesfile_path,'r')
readgrades = gradesfile.readline()

print(readgrades)
'*Assigne 1 grades\n'  # This is the output

print(readgrades)
'*Assigne 1 grades\n' # This is the output


# Here is it working when i don't call the variable

print(gradesfile.readline())
'*Assigne 1 grades\n'  # This is the output

print(gradesfile.readline())
'*Columns\n'   # This is the output

print(gradesfile.readline())
'*ID\t   grade\n'  # This is the output



RE: read file assistance - squenson - Dec-30-2017

When you execute readgrades = gradesfile.readline(), the value of readgrades is fixed until you change it. Therefore, it is normal that on lines 5 and 8, the result is the same. You need to execute another readline() statement to change the value.

The best way to do it is to make a loop like:
for readgrades in gradesfile:
    print(readgrades)
If you want to assign a method to a variable, you do it this way (note the presence or absence of parenthesis):
readgrades = gradesfile.readline # without parenthesis, you assign a method
print(readgrades()) # running the method (returning its value) requires parenthesis
print(readgrades())



RE: read file assistance - flatman123 - Dec-30-2017

(Dec-30-2017, 10:44 AM)squenson Wrote: When you execute readgrades = gradesfile.readline(), the value of readgrades is fixed until you change it. Therefore, it is normal that on lines 5 and 8, the result is the same. You need to execute another readline() statement to change the value.

The best way to do it is to make a loop like:
for readgrades in gradesfile:
    print(readgrades)
If you want to assign a method to a variable, you do it this way (note the presence or absence of parenthesis):
readgrades = gradesfile.readline # without parenthesis, you assign a method
print(readgrades()) # running the method (returning its value) requires parenthesis
print(readgrades())





makes sense, thanks for the assistance, much appreciated.