Module3 File and Process Management
Module3 File and Process Management
Python – Module 3
Scripting, File Handling, and Process
Management
Working with Files and Folders
• • Python’s os module provides functions to
interact with the file system.
• • Use cases: file automation, backups, logs,
etc.
• • Key concepts: current working directory,
path manipulations.
os.path Module
• • os.path.join(): Joins paths using the correct
separator.
• • os.getcwd(): Get current directory.
• • os.chdir(): Change working directory.
• • Absolute vs Relative Paths.
• • Splitting paths: basename(), dirname(),
split().
Path Validity Checks
• • os.path.exists(path): Checks if a path exists.
• • os.path.isfile(path): Checks if it's a file.
• • os.path.isdir(path): Checks if it's a directory.
• • Example: Safe file operations by checking
paths.
Creating Directories with
os.makedirs()
• • Creates directory, including any intermediate
ones.
• • Example: os.makedirs('C:\example\nested\
folder')
• • Avoids FileNotFoundError for deep paths.
File Operations
• • open(file, mode): Open file for
reading/writing.
• • read(), readlines(): Read file contents.
• • write(): Write to a file.
• • Modes: 'r', 'w', 'a' (read, write, append).
• • Always close files using close() or with
context manager.
pathlib Module
• • pathlib.Path: Modern way to handle paths.
• • Methods: exists(), is_file(), is_dir(), resolve(),
rglob().
• • Works cross-platform and is object-oriented.
Process Execution using
os.system()
• • Runs a shell command.
• • os.system('dir') or os.system('ls')
• • Returns exit status of the command.
subprocess Module
• • subprocess.run(), subprocess.call(): More
powerful than os.system.
• • Can capture stdout, stderr.
• • Recommended for external command
execution.
Replacing Process using os.exec*()
• • os.execl(), os.execv(), etc.: Replace current
process.
• • Example: os.execl('/bin/ls', 'ls', '-l')
• • Used in scripts where you don't return to the
calling process.
Forking Processes with os.fork()
• • Only available on Unix/Linux.
• • Creates child process: returns 0 in child, PID
in parent.
• • Example: Use os.fork() and manage
processes separately.
Killing Processes with os.kill()
• • os.kill(pid, signal): Sends signal to a process.
• • Useful for terminating unwanted or rogue
processes.
• • Combine with fork() for demos.
Summary
• • Use os and pathlib for filesystem operations.
• • subprocess is preferred over os.system.
• • Use exec, fork, kill for advanced process
handling (Unix-based).
• • Combine modules for automation and
scripting tasks.
References
• • Module-3 notes by Prof. Manjusha, SVIT.
• • Python Documentation:
https://docs.python.org/3/library/os.html
• •
https://docs.python.org/3/library/subprocess.
html
• •
https://docs.python.org/3/library/pathlib.htm
l