Essential Python OS & File Operations for Automation
This guide presents a comprehensive collection of Python's os and shutil functions, file handling methods, and practical code examples to help operations engineers automate tasks, manage files and directories, and improve efficiency in modern IT environments.
With the rapid growth of the information age and the increasing integration of the Internet into daily life, the role of IT operations has become more critical. Traditional manual operations can no longer meet business demands, so automation—built on standardized, procedural foundations—is essential for improving efficiency, reducing costs, and enhancing service quality.
Common os module functions
os.getcwd()– Get the current working directory. os.listdir(path) – List all files and directories in the specified path. os.remove(path) – Delete a single file. os.removedirs(path) – Remove multiple directories (use with caution). os.path.isfile(path) – Check if a path points to a file. os.path.isdir(path) – Check if a path points to a directory. os.path.isabs(path) – Determine whether a path is absolute. os.path.exists(path) – Verify that a path exists. os.path.split(path) – Split a path into directory and file name. os.path.splitext(path) – Separate the file name from its extension. os.path.dirname(path) – Get the directory component of a path. os.path.basename(path) – Get the file name component of a path. os.system(command) – Execute a shell command. os.getenv(key) / os.putenv(key, value) – Read and set environment variables. os.linesep – Platform-specific line separator (e.g., "\r\n" on Windows). os.name – Identify the operating system ("nt" for Windows, "posix" for Unix/Linux). os.rename(old, new) – Rename a file or directory. os.makedirs(path) – Create nested directories. os.mkdir(path) – Create a single directory. os.stat(path) – Retrieve file attributes. os.chmod(path, mode) – Change file permissions. os.exit() – Terminate the current process (Python 2.4+). os.path.getsize(path) – Get the size of a file.
File handling with open()
Modes: w (write), a (append), r+ (read/write), w+ (read/write, truncates), a+ (read/write, appends), rb, wb, ab, rb+, wb+, ab+ (binary variants). fp.read([size]) – Read up to *size* bytes. fp.readline([size]) – Read a single line, optionally limited by *size*. fp.readlines() – Read all lines into a list. fp.write(str) – Write a string (no automatic newline). fp.writelines(seq) – Write an iterable of strings. fp.close() – Close the file. fp.flush() – Flush the internal buffer to disk. fp.fileno() – Return the file descriptor. fp.isatty() – Check if the file is a terminal device. fp.tell() – Get the current file pointer position. fp.seek(offset, whence=0) – Move the file pointer; *whence* = 0 (start), 1 (current), 2 (end). fp.truncate([size]) – Truncate the file to *size* bytes (default current position).
Directory and file operations with shutil
shutil.copyfile(src, dst)– Copy a file. shutil.copy(src, dst) – Copy a file; *dst* can be a directory. shutil.copytree(src, dst) – Recursively copy an entire directory tree (destination must not exist). shutil.move(src, dst) – Move a file or directory. os.rmdir(path) – Remove an empty directory. shutil.rmtree(path) – Remove a directory and all its contents. os.chdir(path) – Change the current working directory.
Key file‑pointer methods explained
seek(offset, whence)– Move the pointer; *whence* = 0 (from start), 1 (from current), 2 (from end). tell() – Return the current pointer offset. truncate(n) – Shorten the file to *n* bytes; if *n* exceeds the file size, behavior varies by OS. readline(n) – Read a line up to *n* bytes; if *n* is omitted, reads the full line. readlines() – Read all lines into a list. read() – Read the entire file content.
Practical example demonstrating file pointer behavior
fso = open("f:\\a.txt", 'w+')
print fso.tell() # 0 – file is empty after opening with w+
fso.write("abcde
") # Write 7 bytes (including
)
print fso.tell() # 7
fso.write("fghwm") # Write 5 more bytes
print fso.tell() # 12
fso.seek(1, 0) # Move to offset 1 from start
print fso.tell() # 1
print fso.readline() # Reads from position 1, outputs "bcde"
print fso.tell() # 7 – after reading the line
fso.truncate(8) # Truncate to 8 bytes, resulting content "abcde
f"
print fso.tell() # Still 7 (position unchanged by truncate)
print fso.readline() # Reads from position 8, outputs "f"This collection of functions and examples equips operations engineers with the essential Python tools to script routine tasks, manipulate files and directories programmatically, and build reliable automation workflows.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
