Reputation: 41
I am attempting to read a file per line (further down the line I will be splitting each line by comma). My program is reading that there are 10 lines with text in them however when I use the readline()
function it returns a blank string.
I have tried to put the readline
inside the linecount
function, but that failed and I have also tried it with and without the file loop parameter.
QFile = open("questions.txt", "r")
lineCount = 0
fileloop = 0
for line in QFile:
if line != "/n":
lineCount = lineCount + 1
print(lineCount)
while fileloop < lineCount:
print(QFile.readline(fileloop))
fileloop += 1
A sample of my file
What is the name of the rugby compition with Scotland, England, Ierland, Wales, France and Italy?,Six Nations,Sport,1
What’s the maximum score you can achieve in 10-pin bowling?,300,Sport,1
Which horse is the only three-time winner of the Grand National?,Red Rum,Sport,1
Which country won both the men's and women's Six Nations in 2020?,England,Sport,1
Upvotes: 0
Views: 76
Reputation: 9509
If you loop through a file a second time, you have to reset the file pointer first with QFile.seek(0)
as indicated in the comments.
Getting the line count can be shortened down to
lineCount = len(QFile.readlines())
QFile.seek(0)
Or even better, just combine everything into one loop which is better performance-wise. If you are actually trying to print out everything except blank lines you would want something more along the lines of
nonEmptyLineCount = 0
for line in QFile:
if line != '\n':
print(line)
nonEmptyLineCount += 1
Or alternatively
data = filter(lambda x: x != '\n', QFile)
for line in data:
print(data)
Upvotes: 1