Search code examples
pythontext

Reading text files. Streaming output truncated to the last 5000 lines


I am trying to read and print text with python code but in colab, only last 5000 lines are printed and in python, it prints even less than that.

I have tried this code.

import sys

def get_filename():
    """Prompts the user for a filename and returns it."""
    filename = input("Enter a filename: ")
    return filename

def process_file(filename):
    """Reads the contents of a file and prints each line to the terminal."""
    with open(filename, "r", encoding="utf8") as file:
        for line in file:
            sys.stdout.write(line)  # Write each line to stdout
            sys.stdout.flush()

def main():
    """Calls get_filename and then calls process_file with the name returned by get_filename."""
    filename = get_filename()
    process_file(filename)

if __name__ == "__main__":
    main()

Solution

  • Experiencing similar in colab, resolved as follows:

    • declare a counter (e.g. cnt=n)
    • in your for-loop, have the counter increment and stop where you want it to (in this example at 10th iteration:
    for line in file:
      if cnt<=10:
        print(line)      
      else:
        break
      cnt+=1