How to read a text file into a list or an array with Python
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Reading a text file into Python is simple, but the right approach depends on what you want the result to look like. Sometimes you need raw lines, sometimes stripped strings, and sometimes you need parsed numbers or a NumPy array.
The Most Common Case: A List Of Lines
If you want one list element per line, open the file and iterate over it.
This is a good default because:
- it is easy to read
- it removes trailing newlines cleanly
- it works well for ordinary text files
If you want to keep the newline characters, use fh.readlines() instead.
Reading The Whole File As One String
Sometimes the first step is not a list at all. If you need the entire text, read it as one string and split later if necessary.
This is useful when you want paragraph-level processing or regular-expression parsing across the whole file.
Converting Lines To Numbers
If each line contains a number, convert as you read.
This gives you a Python list of integers rather than a list of strings.
If malformed input is possible, add error handling.
Reading Into A NumPy Array
If you really mean array in the numerical computing sense, use NumPy rather than a plain Python list.
This is the better choice for scientific code, matrix operations, or machine learning preprocessing.
Structured Delimited Files
If the file is comma-separated or otherwise structured, do not treat it like arbitrary text. Parse it with the right tool.
For simple ad hoc data, splitting may be enough:
But once quoting or escaping matters, use the csv module.
Large Files Need Streaming
For large files, do not read everything into memory unless you have a reason. Iterate and process line by line.
This is still collecting matching lines, but it avoids loading the entire file at once.
pathlib Makes File Code Cleaner
If you prefer modern path handling, pathlib works well.
This is concise, though it reads the whole file into memory first.
Common Pitfalls
The most common mistake is forgetting the file's encoding. Using encoding="utf-8" explicitly avoids many cross-platform surprises.
Another mistake is accidentally keeping newline characters and then wondering why string comparisons fail.
Developers also sometimes read a giant file into memory when a streaming loop would be simpler and safer.
Finally, if the file is really CSV or another structured format, use a parser instead of treating it as plain text lines.
Summary
- Use a list comprehension over the file handle to read one stripped string per line.
- Use
read()when you need the whole file as one string. - Convert during reading if the lines represent numbers.
- Use NumPy if you need a numeric array rather than a Python list.
- Stream large files and use proper parsers for structured formats.

