To learn how to read TXT file in Python, start with the built-in open() function and a with statement. The most common pattern is with open(“file.txt”, “r”, encoding=”utf-8″) as file: followed by text = file.read(). The context manager automatically closes the file, and specifying UTF-8 makes text handling more predictable across computers.

That short example is enough for a small document, but real projects often need to process one line at a time, handle large files, resolve paths, preserve or remove line breaks, and recover from encoding errors. This guide explains the major techniques with practical code and clear advice about when to use each one.

Basic Syntax for Reading a TXT File in Python

Python’s built-in open() function creates a file object. When you open a file in text mode, Python reads decoded strings rather than raw bytes. The official Python documentation recommends specifying an encoding, and UTF-8 is the modern default choice unless you know the source uses another encoding.

with open("notes.txt", "r", encoding="utf-8") as file:
    content = file.read()

print(content)

The first argument is the file path. The second argument, “r”, means read mode. The encoding argument tells Python how to translate stored bytes into Unicode characters. The variable content receives one string containing the entire file.

Why Use the with Statement?

The with statement creates a context manager. When the indented block ends, Python closes the file automatically, even if an exception occurs while the content is being processed. That behavior reduces resource leaks and avoids problems caused by leaving file handles open.

You can open a file manually and call close(), but the context-manager pattern is safer and more concise. It is the best default for most scripts, web applications, data tools, and automation jobs.

How to Read the Entire TXT File at Once

Use file.read() when the document is reasonably small and you want to search, display, transform, or pass the complete content to another function. The return value is a Python string, so normal string methods such as replace(), split(), lower(), and count() are available.

with open("article.txt", "r", encoding="utf-8") as file:
    article = file.read()

word_count = len(article.split())
print(f"Approximate words: {word_count}")

This technique is simple, but the full string must fit in memory. A two-kilobyte note is trivial; a multi-gigabyte log is not. For large files, iterate over the file object one line at a time.

Read Only a Specific Number of Characters

The read() method accepts an optional size argument. Calling file.read(100) reads up to 100 characters from the current position. A later call continues from where the previous read ended.

with open("preview.txt", "r", encoding="utf-8") as file:
    first_part = file.read(100)
    next_part = file.read(100)

print(first_part)

Chunked reads are useful for previews or streaming-style processing. Remember that text characters and storage bytes are not always one-to-one in encodings such as UTF-8, but Python handles decoding before returning the string.

How to Read a TXT File Line by Line

Iterating over the file object is the preferred approach for a large text document. Python retrieves one line at a time instead of placing the entire file in one string, keeping memory use low.

with open("server.log", "r", encoding="utf-8") as file:
    for line_number, line in enumerate(file, start=1):
        print(line_number, line.rstrip("\n"))

The enumerate() function adds a line number. The rstrip(“\n”) call removes the newline character at the end of each line while preserving other whitespace. Using plain strip() would also remove spaces and tabs from both ends, which may be undesirable when indentation matters.

Process Only Matching Lines

Line-by-line reading works well for logs, exports, and reports where you need only certain records. The following example prints lines containing the word ERROR without loading the whole file.

with open("application.log", "r", encoding="utf-8") as file:
    for line in file:
        if "ERROR" in line:
            print(line.rstrip())

For case-insensitive matching, compare against line.lower() or use a regular expression. Keep the original line if capitalization needs to be preserved in the output.

How to Read All Lines Into a List

The readlines() method returns a list in which each element represents one line. It is convenient when you need indexing, repeated passes, sorting, slicing, or list-based processing.

with open("tasks.txt", "r", encoding="utf-8") as file:
    lines = file.readlines()

print(lines[0])
print(f"Total lines: {len(lines)}")

Newline characters normally remain attached to the elements. Use a list comprehension if you need cleaned lines.

with open("tasks.txt", "r", encoding="utf-8") as file:
    tasks = [line.rstrip("\n") for line in file]

Like read(), readlines() stores the full content in memory. It is appropriate for small and medium files but not the best choice for a huge log or dataset.

How to Read a TXT File With pathlib

The pathlib module provides an object-oriented way to work with paths. Its Path.read_text() method is concise when you want an entire text file, and the same Path object can be used to test existence, examine the filename, or construct related paths.

from pathlib import Path

path = Path(“data”) / “message.txt”
content = path.read_text(encoding=”utf-8″)
print(content)

read_text() opens, reads, and closes the file for you. It is excellent for configuration snippets, templates, test fixtures, and short documents. Use path.open() with a loop when the file is too large to read at once.

from pathlib import Path

path = Path("logs") / "today.txt"

with path.open("r", encoding="utf-8") as file:
    for line in file:
        process_line = line.rstrip("\n")
        print(process_line)

Understanding File Paths

Many beginners see FileNotFoundError even though the TXT file exists. The usual cause is a mismatch between the script’s current working directory and the folder where the user expects Python to look.

A relative path such as “notes.txt” is resolved from the current working directory, not necessarily from the directory containing the Python script. Use Path.cwd() to inspect that location during debugging.

from pathlib import Path

print(Path.cwd())

Use a Path Relative to the Script

When a resource is stored beside the script, build the path from __file__. This makes the program more reliable when launched from another directory.

from pathlib import Path

base_dir = Path(__file__).resolve().parent
file_path = base_dir / "notes.txt"
content = file_path.read_text(encoding="utf-8")

In notebooks and some interactive environments, __file__ is not defined. Use the notebook’s working directory, an uploaded-file path, or a configured project directory instead.

How to Handle TXT File Encoding

Text encoding is the rule used to map bytes to characters. UTF-8 can represent a broad range of scripts and symbols, so it is a dependable default for new files. A legacy export may instead use Windows-1252, Latin-1, UTF-16, or another encoding.

If Python raises UnicodeDecodeError, identify the source encoding rather than deleting characters blindly. When the file came from a known system, check that system’s export settings or documentation.

with open("legacy.txt", "r", encoding="cp1252") as file:
    content = file.read()

The errors argument controls what happens when decoding encounters an invalid byte sequence. errors=”replace” substitutes a replacement character, while errors=”ignore” drops undecodable data. Both can hide information loss, so use them only when that tradeoff is acceptable.

with open("damaged.txt", "r", encoding="utf-8", errors="replace") as file:
    content = file.read()

Reading UTF-8 Files With a BOM

Some software writes a byte-order mark at the beginning of a UTF-8 file. Python’s utf-8-sig codec reads UTF-8 and removes that leading marker from the returned text.

with open("export.txt", "r", encoding="utf-8-sig") as file:
    content = file.read()

This is particularly useful for files exported from certain Windows or spreadsheet applications. If there is no BOM, utf-8-sig can still read ordinary UTF-8 content.

Reading Delimited Data From a TXT File

A TXT file may contain records separated by tabs, pipes, commas, or semicolons. Although you can split each line manually, Python’s csv module handles quoting and delimiters more reliably.

import csv

with open("customers.txt", "r", encoding="utf-8", newline="") as file:
    reader = csv.reader(file, delimiter="\t")
    for row in reader:
        name, email, country = row
        print(name, email, country)

Use csv.DictReader when the first row contains column names. Each record then behaves like a dictionary, which makes code easier to understand and less dependent on column order.

import csv

with open("products.txt", "r", encoding="utf-8", newline="") as file:
    reader = csv.DictReader(file, delimiter="|")
    for row in reader:
        print(row["product_name"], row["price"])

Common Errors and How to Fix Them

Reliable file handling requires more than a successful read() call. The most frequent errors reveal something useful about the path, permissions, encoding, or expected structure.

FileNotFoundError

The path does not point to an existing file from the current working directory. Print the resolved path, confirm spelling and capitalization, and verify that the extension is visible. On case-sensitive systems, Notes.txt and notes.txt are different names.

from pathlib import Path

path = Path("notes.txt")
print(path.resolve())
print(path.exists())

PermissionError

The process cannot access the file. Check operating-system permissions, confirm that the path refers to a file rather than a protected directory, and avoid system locations unless the application genuinely needs them.

Do not solve routine permission issues by running every script as an administrator. Place user data in an appropriate project or documents folder and grant only the access required.

UnicodeDecodeError

The selected encoding does not match the stored bytes. Reopen the file with the correct encoding or export a fresh UTF-8 copy from the source application. Guessing with errors=”ignore” may silently remove important characters.

IsADirectoryError

The path points to a directory rather than a file. Append the intended filename or iterate through the directory and select files that match the expected extension.

Best Practices for Reading Text Files

Good file-reading code is explicit, memory-aware, and careful with external input. These practices prevent many bugs before they reach users.

  • Use a with statement or Path.read_text() so files close correctly.
  • Specify encoding=”utf-8″ for new and known UTF-8 documents.
  • Iterate line by line for large files.
  • Preserve meaningful whitespace by using targeted methods such as rstrip(“\n”).
  • Construct paths with pathlib instead of manual string concatenation.
  • Validate file existence, type, and size when the path comes from a user.
  • Treat uploaded text as untrusted data and never execute its contents automatically.
  • Log encoding substitutions or skipped records when data quality matters.

If you need a clean sample document for testing, create or download a UTF-8 file with TXT File Maker and place it in the same project folder as your script. Testing with multilingual characters and blank lines is a good way to confirm that your code handles real-world content.

Frequently Asked Questions

These answers summarize the most common Python TXT-reading questions. The examples target modern Python 3.

What is the easiest way to read a TXT file in Python?

Use with open(“file.txt”, “r”, encoding=”utf-8″) as file: and then call file.read(). This returns the entire file as a string and closes the file automatically after the block.

How do I read a TXT file line by line?

Open it with a with statement and loop directly over the file object. This method is memory-efficient because Python does not need to load the whole document at once.

What is the difference between read() and readlines()?

read() returns one string containing the full file. readlines() returns a list whose elements are the individual lines, usually with newline characters still attached.

How do I read a file from another folder?

Pass a relative or absolute path to open(), or construct the path with pathlib.Path. Check Path.cwd() if a relative path points somewhere unexpected.

Why does Python say my TXT file does not exist?

The script is probably resolving a relative path from a different working directory, or the filename, capitalization, or extension does not match. Print the resolved path and check it in the file manager.

Which encoding should I use?

Use UTF-8 for new files and whenever the source is known to be UTF-8. If the file came from a legacy system, use the documented source encoding rather than guessing.

How do I read a very large TXT file?

Loop over the file object one line at a time or process fixed-size chunks. Avoid read() and readlines() when the complete content may exceed available memory.

Final Thoughts

The best answer to how to read TXT file in Python is to begin with a context manager, explicit UTF-8 encoding, and the method that matches the file size. Use read() for a small complete document, iterate over the file for large or streaming work, use readlines() when a list is truly useful, and choose pathlib for clean path handling.

Once those basics are in place, pay attention to paths, encodings, delimiters, and error handling. These details turn a demonstration into reliable code that can process real notes, exports, logs, and user-provided text safely.