Read file

2 snippets across 2 stacks - Bash & Linux, Python

SHBash & Linux

Display File Contents

SH · File Content
Syntax
cat [options] file...
Example
cat server.log
cat -n deploy.sh
cat header.html body.html footer.html > page.html

Note -n adds line numbers, -A shows invisible characters (tabs, line endings). cat is best for short files; use less for anything longer than a screenful. Concatenating multiple files into one is where cat gets its name.

PYPython

Reading Files

PY · File I/O
Syntax
with open(path, 'r') as f:
    content = f.read()
Example
with open("config.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content[:50])

# Read line by line (memory efficient)
with open("data.log") as f:
    for line in f:
        print(line.strip())

Note Always specify encoding='utf-8' explicitly. The default varies by platform. Iterating line-by-line avoids loading the entire file into memory.

Frequently asked questions

How do you read file?
This task is covered in 2 stacks on this page: Bash & Linux, Python. The "Display File Contents" snippet in Bash & Linux uses `cat [options] file...`.
Which command does the Bash & Linux example use?
The "Display File Contents" snippet uses `cat [options] file...`, from the File Content section of the Bash & Linux cheat sheet.
Which stacks cover "read file" on this page?
Bash & Linux, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Display File Contents": -n adds line numbers, -A shows invisible characters (tabs, line endings). cat is best for short files; use less for anything longer than a screenful. Concatenating multiple files into one is where cat gets its name.