title: Manipulate files and directories
description: Python's os module provides the function of detecting the operating system type:
Manipulate files and directories
When writing Python scripts across platforms, the most common pitfalls are hard-coded path separators, adaptation system commands, or simply not knowing which operating system the current code is running on. At this time,osfamily (includingos.path)、shutil, and Python 3.4 is super easy to use.pathlib, is your savior!
This article will take you through the core tool chain for file and directory operations in Python, and give you a bunch of security tips and practical cases, so that the scripts you write are clear and reliable, and can run smoothly on Windows / Linux / macOS.
Operating system type detection
You must first understand the running environment of the script before you can make targeted adaptations - such as path processing, calling system commands, etc.
💡 System corresponding to common logos:
posix:Linux, macOS, BSD and other Unix-like systemsnt:Windows system
If you need to obtain more detailed kernel, host name and other information (only supports Unix-like systems), you can do this:
⚠️ Note: Call directly on Windowsos.uname()An error will be reported, so you must judge first.os.name。
Environment variable operations
All system environment variables are stored in dictionary-like structuresos.environinside.
Although it can be assigned directly, it is highly recommended to use.get()Method ** to avoid throwing because the variable does not existKeyError。
Writing this way is not only safer, but also allows you to provide fallback solutions elegantly.
File and directory operations
Core Principles💡
Never manually concatenate path strings (e.g.'/Users/xxx' + 'test.txt')。
Different systems have different delimiters - Windows uses\, for Unix-like/. Manual splicing breaks cross-platform compatibility and causes scripts to crash silently.
Here are two path tools: classic but highly compatibleos.path, as well as more modern and elegantpathlib。
Classic path tool: os.path
Although it is now more recommendedpathlib,butos.pathIt has the best compatibility (common to Python 2.x/3.x) and is still used by many old projects. It is still necessary to master it:
Modern path tools: pathlib (preferred for Python 3.4+)
pathlibUse an object-oriented method to process paths and turn the paths into objects instead of strings. The code is simpler and more readable. It can be calledos.pathcomprehensive replacement.
For newbies,pathlibThe syntax is more like natural language, and it is recommended to use it directly in new Python projects.
Directory operations
Doesn't workosstillpathlib, the underlying logic is similar, but the syntax is different. Here the two methods are put together for easy comparison:
Use os module
Use pathlib
File operations
Use os module
Use pathlib
Advanced file operations
os / pathlibIt can cover basic needs, but advanced operations such as copying files, recursively deleting, and moving large directories are best left toshutilModule (short for "shell utilities"). It encapsulates many efficient and safe file operations, which is much more reliable than manually implementing them yourself.
Use
shutil.rmtreeBe sure to make sure the variable name is correct beforehand. It is best to add a second confirmation to avoid deleting it by mistake.
Practical Tips
1. List all subdirectories under the current directory
2. Search files recursively
For example, find out the file names in the current directory and all subdirectories containinglogFiles:
3. Calculate the total size of the directory
Summarize
- Environment Detection: Use
os.nameQuick judgment system, can be further used under Unix-likeos.uname()Get details. - Path Handling: Python 3.4+ preferred
pathlib(Object-oriented, support/operator, chain call), used in old projects or when compatibility with Python 2 is requiredos.path。 - Basic Directory/File Operations: Use
osorpathlibFor the corresponding methods, pay attention to cross-platform and exception-handling. - Complex operations: copy, recursive deletion, move, etc. are handed over
shutil, powerful and secure package. - Safety Reminder:
- Do not print easily in production environment
os.environall content. - Delete operations (especially
rmtree) must be judged or confirmed twice before proceeding. - Try to use it before operation
.exists()、.is_file()、.is_dir()Check status to avoid unnecessary exceptions.
Mastering this tool chain, you can write concise and robust cross-platform file operation logic, whether it is daily scripts or project code.

