.read() reads the whole file into one string. This is the simplest way to read a file, and it is fine for small and medium files.
The program
python
# create a small file first, so there is something to read with open("poem.txt", "w", encoding="utf-8") as f: f.write("Roses are red,\nViolets are blue,\nPython is fun,\nAnd so are you.\n") with open("poem.txt", encoding="utf-8") as f: content = f.read() print(content, end="") print("Characters:", len(content))
output
Roses are red, Violets are blue, Python is fun, And so are you. Characters: 64
How it works
open("poem.txt")opens the file in read mode. Read mode ("r") is the default, so you do not need to write it.contentis one string. The line breaks are inside it as\ncharacters, and each one counts as a character inlen(content).- The file is closed when the
withblock ends.contentis still available after that, because it is a normal string in memory.
When the file is missing
If the file does not exist, open() raises FileNotFoundError. Catch it to show a clear message instead of a traceback:
python
filename = "missing.txt" try: with open(filename, encoding="utf-8") as f: content = f.read() except FileNotFoundError: print(f"Could not find {filename}")
output
Could not find missing.txt
For a very large file (for example a log file of several gigabytes), read() would load all of it into memory. Read it line by line instead.