Oo笑容太甜oO/

Python之OS模块


The os module is a part of the standard library, or stdlib, within Python 3. This means that it comes with your Python installation, but you still must import it.

Sample code using os:

import os

All of the following code assumes you have os imported. Because it is not a built-in function, you must always import it. It is a part of the standard library, however, so you will not need to download or install it separately from your Python installation.

curDir = os.getcwd()
print(curDir)

The above code will get your current working directory, hence "cwd."

To make a new directory:

os.mkdir('newDir')

To change the name of, or rename, a directory:

os.rename('newDir','newDir2')

To remove a directory:

os.rmdir('newDir2')

With the os module, there are of course many more things we can do. In many scenarios, however, the os module is actually becoming outdated, as there is a superior module to get the job done. We will get to those soon enough. It is still a good idea to at least know some of the basics of the os module. I especially like to use it to create directories. If you ever create a setup.py file, the creation of directories and the placing of files within them will be essential.