0

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
5
  • 1
    After the for loop the file pointer will be at the end of the file, you need to rewind the file or close and reopen it, or print the lines in the for loop while counting Commented Mar 8, 2022 at 20:05
  • 2
    Note: the newline character is "\n", not "/n". Commented Mar 8, 2022 at 20:10
  • Thanks, adding QFile.seek(0) between the 2 loops fixed the issues Commented Mar 8, 2022 at 20:12
  • You don't have a true line count since you are ignoring empty lines line != "/n", which will cause your while loop to finish looping over the file early, and the last few lines won't be printed. Is it your intention to print out everything except empty lines? Commented Mar 8, 2022 at 20:38
  • Yes, I don't need to count empty lines (and my file should not contain any of them part from at the end which I don't need). Commented Mar 9, 2022 at 21:41

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.