Once you’ve opened up a file, you’ll want to read or write to the file. First off, let’s cover reading a file. There are multiple methods that can be called on a file object to help you out.
read()
takes a number as a parameter and reads from the file based on that number of bytes. If no argument is passed, or None
or -1
is passed, then the entire file is read.
readline()
takes a number as a parameter and reads at most that number of characters from the line. This continues to the end of the line and then wraps back around. If no argument is passed, or None
or -1
is passed, then the entire line (or rest of the line) is read.
readlines()
reads the remaining lines from the file object and returns them as a list.
Shawn Bardong on Feb. 16, 2020
Appreciate the tutorial, but in which directory are you putting the text file? you need to run the script in the same directory as the text file? How should you separate your data and scripts into different directories/folders?