dodle
July 10th, 2010, 01:48 AM
This isn't really a problem, more of a curiosity. If I want to open and read a text file multiple times, why do I have to re-open the file each time I read it? It seems like I would only need to open it once, then I could read it as many times as I wanted until I closed it.
Here is the example code. When I try to get the second line at a different point in my code it's telling me that the file is empty. It appears that each time the file is read, the variable used to open the file is cleared to an empty string:
# Opening a Single File
file = open("test.txt", "r") # Open a text file
first_line = file.read().split("\n")[0]
second_line = file.read().split("\n")[1]
last_line = file.read().split("\n")[-1]
print "First Line: %s\nSecond Line: %s\nLast Line: %s" % (first_line, second_line, last_line)
file.close()
This, on the other hand, does work:
# Opening a Single File Multiple Times
file = open("test.txt", "r") # Open a text file to get first line
first_line = file.read().split("\n")[0]
file = open("test.txt", "r") # Open a text file to get second line
second_line = file.read().split("\n")[1]
file = open("test.txt", "r") # Open a text file to get last line
last_line = file.read().split("\n")[-1]
print "First Line: %s\nSecond Line: %s\nLast Line: %s" % (first_line, second_line, last_line)
file.close()
Like I said, it's not really a problem. I just want to understand why Python acts this way.
Here is the example code. When I try to get the second line at a different point in my code it's telling me that the file is empty. It appears that each time the file is read, the variable used to open the file is cleared to an empty string:
# Opening a Single File
file = open("test.txt", "r") # Open a text file
first_line = file.read().split("\n")[0]
second_line = file.read().split("\n")[1]
last_line = file.read().split("\n")[-1]
print "First Line: %s\nSecond Line: %s\nLast Line: %s" % (first_line, second_line, last_line)
file.close()
This, on the other hand, does work:
# Opening a Single File Multiple Times
file = open("test.txt", "r") # Open a text file to get first line
first_line = file.read().split("\n")[0]
file = open("test.txt", "r") # Open a text file to get second line
second_line = file.read().split("\n")[1]
file = open("test.txt", "r") # Open a text file to get last line
last_line = file.read().split("\n")[-1]
print "First Line: %s\nSecond Line: %s\nLast Line: %s" % (first_line, second_line, last_line)
file.close()
Like I said, it's not really a problem. I just want to understand why Python acts this way.