The simplest way to read a text file

To read a text file in Python, use the open() function with the filename and the mode 'r' (for read). The most straightforward approach is to read the entire file into a single string using the read() method.

Here is the actual code:

with open('myfile.txt', 'r') as file: content = file.read() print(content)

The with statement ensures Python closes the file automatically when you are done, even if something goes wrong. This is the safest way to work with files because you do not have to remember to close them yourself.

If your file is in a different folder, include the path: open('Documents/myfile.txt', 'r') on Windows or Mac, or open('Documents/myfile.txt', 'r') on Linux. Python reads the file from your current working directory unless you give it a full path.

Key Takeaways

  • Use open(filename, 'r') with a with statement to read a file safely and automatically close it when done.
  • The read() method loads the entire file into memory as one string, which works well for small files but can be slow for very large ones.
  • The readlines() method returns a list where each item is one line, making it easier to work with individual lines of text.
  • A for loop reads one line at a time without loading the whole file into memory, which is the best choice for large files.
  • Always include the correct file path if your file is not in the same folder as your Python script.

Reading one line at a time with a loop

When your file is large, reading the entire thing into memory at once can slow down your program. Instead, use a for loop to read one line at a time.

with open('myfile.txt', 'r') as file: for line in file: print(line.strip())

The strip() method removes the newline character at the end of each line, so your output does not have extra blank lines. Without it, print() adds its own newline, creating double spacing.

This approach is much faster for files with thousands or millions of lines because Python only keeps one line in memory at a time. It is the standard choice for processing log files, data files, or any text file larger than a few megabytes.

Reading all lines into a list

If you need to work with all the lines but want them organized as separate items, use the readlines() method. It returns a list where each item is one line, including the newline character at the end.

with open('myfile.txt', 'r') as file: lines = file.readlines() for line in lines: print(line.strip())

This is useful when you need to access lines in any order, count them, or modify them before printing. For example, you could reverse the list with lines.reverse() or sort it with lines.sort().

The downside is that readlines() loads the entire file into memory at once, just like read(). For very large files, the for loop approach is faster and uses less memory.

Handling files that do not exist or cannot be read

If you try to open a file that does not exist, Python stops and shows an error. You can prevent this by using a try and except block to catch the error and handle it gracefully.

try: with open('myfile.txt', 'r') as file: content = file.read() except FileNotFoundError: print("The file was not found.")

Common errors include FileNotFoundError (the file does not exist), PermissionError (you do not have permission to read it), and UnicodeDecodeError (the file is not actually a text file, or it uses an encoding Python does not recognize by default).

If you encounter a UnicodeDecodeError, the file may be encoded in a format other than UTF-8. Try specifying the encoding: open('myfile.txt', 'r', encoding='latin-1'). Common alternatives are 'iso-8859-1', 'cp1252' (Windows), or 'utf-16'.

Reading specific parts of a file

Sometimes you only need certain lines or a specific section. You can skip lines, read only the first few, or stop when you reach a certain point.

To read only the first 10 lines:

with open('myfile.txt', 'r') as file: for i, line in enumerate(file): if i >= 10: break print(line.strip())

To skip the first 5 lines and then read the rest:

with open('myfile.txt', 'r') as file: for i, line in enumerate(file): if i < 5: continue print(line.strip())

The enumerate() function gives you both the line number (starting at 0) and the line itself, so you can make decisions based on position.

Working with structured text files

If your file contains data separated by commas, tabs, or spaces, you can split each line into parts and work with them individually.

with open('data.txt', 'r') as file: for line in file: parts = line.strip().split(',') print(parts[0], parts[1])

The split() method breaks the line at each comma and returns a list. parts[0] is the first item, parts[1] is the second, and so on. If your file uses tabs instead, use split('\t'). For spaces, use split() with no argument, which splits at any whitespace.

For more complex data files (especially CSV files with quoted fields or special characters), Python's built-in csv module handles the splitting for you and is more reliable than manual splitting.

Frequently Asked Questions

What is the difference between read(), readlines(), and a for loop?

read() loads the entire file as one string. readlines() loads the entire file as a list of lines. A for loop reads one line at a time without loading everything into memory. Use read() for small files you need as a single string, readlines() when you need all lines as a list, and a for loop for large files or when processing line by line.

Do I have to use the with statement?

No, but you should. Without with, you must call file.close() yourself. If your code crashes before reaching close(), the file stays open and can cause problems. The with statement closes the file automatically, even if an error occurs.

What does the 'r' in open() mean?

'r' means read mode — you can only read the file, not change it. Other modes include 'w' (write, which erases the file first), 'a' (append, which adds to the end), and 'r+' (read and write). Always use 'r' unless you intend to modify the file.

How do I read a file from a different folder?

Include the path in the filename: open('folder/subfolder/myfile.txt', 'r') for a relative path (relative to where your script is), or open('/home/username/Documents/myfile.txt', 'r') for an absolute path (the full address from the root of your system). On Windows, you can also use backslashes: open('folder\\myfile.txt', 'r').

What should I do if I get a UnicodeDecodeError?

The file is encoded in a format Python does not recognize. Try specifying the encoding: open('myfile.txt', 'r', encoding='latin-1') or encoding='cp1252'. If you do not know the encoding, try 'utf-8' (the default), 'latin-1', or 'cp1252' in order. Some text editors can tell you the encoding if you open the file and check its properties.