0
0
PythonHow-ToBeginner · 3 min read

How to Read a File in One Line Python: Simple Syntax & Example

You can read a file in one line in Python using open('filename').read(). This opens the file, reads all its content as a string, and returns it immediately.
📐

Syntax

The one-line syntax to read a file is open('filename').read(). Here:

  • open('filename') opens the file in read mode by default.
  • .read() reads the entire content of the file as a string.

This returns the full text inside the file in one step.

python
content = open('example.txt').read()
💻

Example

This example shows how to read the whole content of a file named example.txt in one line and print it.

python
with open('example.txt', 'w') as f:
    f.write('Hello, world!\nThis is a test file.')

content = open('example.txt').read()
print(content)
Output
Hello, world! This is a test file.
⚠️

Common Pitfalls

One common mistake is not closing the file after reading, which can cause resource leaks. Using open().read() alone does not close the file automatically.

Better practice is to use a with statement to open and read the file, which closes it automatically.

python
wrong = open('example.txt').read()  # File not closed explicitly

with open('example.txt') as f:
    right = f.read()  # File closed automatically
📊

Quick Reference

Tips for reading files in one line:

  • Use open('filename').read() for quick scripts.
  • Prefer with open('filename') as f: content = f.read() to ensure file closes.
  • Reading large files with .read() loads all content into memory.

Key Takeaways

Use open('filename').read() to read a file's full content in one line.
Always close files to avoid resource leaks; use with for automatic closing.
Reading large files with .read() loads everything into memory at once.
For quick scripts, one-line reading is fine, but prefer with in production code.