I'm writing an assignment to count the number of vowels in a file, currently in my class we have only been using code like this to check for the end of a file:
vowel=0
f=open("filename.txt","r",encoding="utf-8" )
line=f.readline().strip()
while line!="":
for j in range (len(line)):
if line[j].isvowel():
vowel+=1
line=f.readline().strip()
But this time for our assignment the input file given by our professor is an entire essay, so there are several blank lines throughout the text to separate paragraphs and whatnot, meaning my current code would only count until the first blank line.
Is there any way to check if my file has reached its end other than checking for if the line is blank? Preferably in a similar fashion that I have my code in currently, where it checks for something every single iteration of the while loop
Thanks in advance
This question is related to
python
loops
python-3.x
file-io
I discovered while following the above suggestions that for line in f: does not work for a pandas dataframe (not that anyone said it would) because the end of file in a dataframe is the last column, not the last row. for example if you have a data frame with 3 fields (columns) and 9 records (rows), the for loop will stop after the 3rd iteration, not after the 9th iteration. Teresa
Find end position of file:
f = open("file.txt","r")
f.seek(0,2) #Jumps to the end
f.tell() #Give you the end location (characters from start)
f.seek(0) #Jump to the beginning of the file again
Then you can to:
if line == '' and f.tell() == endLocation:
break
for line in f
reads all file to a memory, and that can be a problem.
My offer is to change the original source by replacing stripping and checking for empty line. Because if it is not last line - You will receive at least newline character in it ('\n'). And '.strip()' removes it. But in last line of a file You will receive truely empty line, without any characters. So the following loop will not give You false EOF, and You do not waste a memory:
with open("blablabla.txt", "r") as fl_in:
while True:
line = fl_in.readline()
if not line:
break
line = line.strip()
# do what You want
Source: Stackoverflow.com