Common Python os Module Functions for Automation and File Management
This article provides a concise reference of frequently used Python os and file handling functions, illustrating how to query, manipulate, and manage files, directories, and system attributes for automation tasks with clear code examples.
Below is a collection of frequently used Python methods for automation and file system operations.
os.getcwd() – obtain the current working directory.
os.listdir() – return all files and directory names under a specified path.
os.remove() – delete a single file.
os.removedirs(r"c:\python") – delete multiple directories (use with caution).
os.path.isfile() – check whether a given path is a file.
os.path.isdir() – check whether a given path is a directory.
os.path.isabs() – determine if a path is absolute.
os.path.exists() – verify that a path actually exists.
os.path.split() – split a path into directory and file name components.
Example: import os then os.path.split('/home/swaroop/byte/code/poem.txt') returns ('/home/swaroop/byte/code', 'poem.txt') .
os.path.splitext() – separate the file extension.
os.path.dirname() – get the directory name of a path.
os.path.basename() – get the file name of a path.
os.system() – execute a shell command.
os.getenv() and os.putenv() – read and set environment variables.
os.linesep – platform-specific line separator (e.g., '\r\n' on Windows, '\n' on Linux).
os.name – identify the operating system ('nt' for Windows, 'posix' for Unix/Linux).
os.rename(old, new) – rename a file or directory.
os.makedirs(r"c:\python\test") – create nested directories.
os.mkdir("test") – create a single directory.
os.stat(file) – retrieve file attributes.
os.chmod(file) – modify file permissions or timestamps.
os._exit() – terminate the current process (available in Python 2.4+).
os.path.getsize(filename) – obtain file size.
File operations:
os.mknod("test.txt") – create an empty file.
fp = open("test.txt", "w") – open a file for writing (creates it if it does not exist).
Common file open modes:
w – write (truncate existing file).
a – append (create if needed).
r+ – read/write.
w+ – read/write (truncates).
a+ – read/write with append.
rb , wb , ab – binary read, write, append.
rb+ , wb+ , ab+ – binary read/write/append.
File object methods:
fp.read([size]) – read up to *size* bytes.
fp.readline([size]) – read a single line.
fp.write(str) – write a string (no newline added automatically).
fp.writelines(seq) – write an iterable of strings.
fp.close() – close the file.
fp.flush() – flush internal buffer to disk.
fp.fileno() – return the file descriptor.
fp.isatty() – check if the file is a terminal device.
fp.tell() – get current file pointer position.
fp.seek(offset[, whence]) – move file pointer; *whence* = 0 (start), 1 (current), 2 (end).
fp.truncate([size]) – truncate file to *size* bytes (default current position).
Directory operations (often via os or shutil ):
os.mkdir("file") – create a directory.
shutil.copyfile("oldfile", "newfile") – copy a file.
shutil.copy("oldfile", "newfile") – copy a file; destination may be a directory.
shutil.copytree("olddir", "newdir") – copy an entire directory tree (target must not exist).
os.rename("oldname", "newname") – rename a file or directory.
shutil.move("oldpos", "newpos") – move a file or directory.
os.remove("file") – delete a file.
os.rmdir("dir") – remove an empty directory.
shutil.rmtree("dir") – recursively delete a directory and its contents.
os.chdir("path") – change the current working directory.
Additional notes on file pointer manipulation:
seek(offset, where) – move pointer; *where* = 0 (start), 1 (current), 2 (end).
tell() – returns current pointer position, unaffected by truncate() .
truncate(n) – cut file to *n* characters from the start (or from current position if *n* omitted).
readline(n) – read a line up to *n* bytes; default reads the whole line.
readlines() – read all lines into a list.
read() – read the entire file.
Example demonstrating file operations:
<code>fso = open("f:\\a.txt", 'w+')
print fso.tell() # 0
fso.write("abcde\n")
print fso.tell() # 7
fso.write("fghwm")
print fso.tell() # 12
fso.seek(1, 0)
print fso.tell() # 1
print fso.readline() # reads from position 1, outputs 'bcde'
print fso.tell() # 7
fso.truncate(8)
print fso.tell() # still 7, file now contains 'abcde\nf'
print fso.readline() # reads from position 8, outputs 'f'
</code>The article concludes with a QR code for a free Python public course and additional recommended reading links.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
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.