Once you call read()
to go through a file, the file "pointer" (kinda like cursor) stays at the end of the file, and calling read()
again does nothing since you're already at the end (and there's nothing to read). You need to move the pointer to the beginning of the file with file.seek(0)
.
However, it's better to just read it once to a string and use that:
readMe = open('WriteToFile.txt', 'r')
content = readMe.read()
print( content)
splitMe = content.split('\n')
print(splitMe)
Even better is to use the with
statement, which automatically closes the file for you:
with open('WriteToFile.txt', 'r') as file:
content = file.read()
print(content)
lines = content.split('\n')
print(lines)
Although, if your end goal is to just get the lines, you can use readlines()
:
with open('WriteToFile.txt', 'r') as file:
lines = file.readlines()
print(lines)