The easiest way to read a text file is by looping over the file handle itself, that's actually an iterable (like a list). The loop variable is then assigned the contents of the file, one line at a time. In this video, I demonstrate this technique using a simple text file. Be aware that the newline character at the end of the line also gets read, and you'll normally want to strip it away from your string. Check out the notebooks linked below for more information on file handling in Python.
Embedded video, part of the following courses:
Computer Programming at Queen Mary, University of London
- Jupyter notebook: https://tinyurl.com/yc2tpdfs
Coding for Scientists at Queen Mary, University of London
- Jupyter notebook: https://tinyurl.com/bdef2fcj
Notebooks will open on Google Colab - no installation required
Watch video File I/O in Python: looping over the file handle (it's an iterable!) online without registration, duration hours minute second in high quality. This video was added by user PatchyPython 29 September 2023, don't forget to share it with your friends and acquaintances, it has been viewed on our site 26 once and liked it 0 people.