Python File input/output

  1. In order to read data from a file on our hard disk or write results to a file, we need to open the file for reading or writing.
  2. To open a file for reading, we use the with construct. It introduces a file descriptor which we call poem. We indicate that we open the file for reading by using the mode 'r'

    poem_file = '/home/bon/tmp/poem.txt'
    with open(poem_file, 'r') as poem:
      for line in poem.readlines():
        print(line)
    

    You can find a nice poem here or in poem.txt

  3. Note how readlines reads each line including the newline at the end of each line. print then adds another newline when it prints out the line leading to a double spacing effect. If we prefer single spacing, we can strip off the trailing newline from each line.

    with open(poem_file, 'r') as poem:
      for line in poem.readlines():
        print(line.rstrip())
    
  4. We can also print our poem preceded by line numbers.

    with open(poem_file, 'r') as poem:
        for n, line in enumerate(poem.readlines()):
            print(f'{n+1:>2} {line.rstrip()}')
    
  5. To write to a file, we also use with open but now we use the mode 'w'. Try something like this:

    with open('/tmp/stuff.txt', 'w') as stuff:
        for n in range(20):
           stuff.write(f"{n:2}")
    

Author: Breanndán Ó Nualláin <o@uva.nl>

Date: 2025-09-04 Thu 08:55