Open file

2 snippets across 2 stacks - Bash & Linux, Python

Also written as open files

SHBash & Linux

List Open Files & Ports

SH · Process Management
Syntax
lsof [options]
Example
lsof -i :3000
lsof -u deploy
lsof +D /var/log/
Output
COMMAND   PID   USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
node    19283 deploy   22u  IPv4  284719      0t0  TCP *:3000 (LISTEN)

Note -i :port shows which process is using a port (essential for resolving 'address already in use' errors). -u filters by user. +D lists all open files within a directory. Requires root for other users' processes.

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 open file?
This task is covered in 2 stacks on this page: Bash & Linux, Python. The "List Open Files & Ports" snippet in Bash & Linux uses `lsof [options]`.
Which command does the Bash & Linux example use?
The "List Open Files & Ports" snippet uses `lsof [options]`, from the Process Management section of the Bash & Linux cheat sheet.
Which stacks cover "open 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 "List Open Files & Ports": -i :port shows which process is using a port (essential for resolving 'address already in use' errors). -u filters by user. +D lists all open files within a directory. Requires root for other users' processes.