NameError:名称“os”未在 Python 中定义

NameError:名称“os”未在 Python 中定义

NameError: name ‘os’ is not defined in Python

Python“NameError: name ‘os’ is not defined”发生在我们使用os
模块而不先导入它时。
要解决错误,请
os在使用之前导入模块 – import os

nameerror 名称 os 未定义

下面是错误如何发生的示例。

主程序
BASE = '/user' # ⛔️ NameError: name 'os' is not defined print(os.path.join(BASE, 'articles')) print(os.environ['VIRTUAL_ENV_PROMPT'])

为了解决这个错误,我们必须导入
os模块。

主程序
# 👇️ import os module first import os BASE = '/user' # 👇️ /user/articles print(os.path.join(BASE, 'articles')) # 👇️ (venv) print(os.environ['VIRTUAL_ENV_PROMPT'])

即使该os模块在 Python 标准库中,我们仍然需要在使用前导入它。

Make sure you haven’t used a capital letter o when importing os because module names are case-sensitive.

Also, make sure you haven’t imported os in a nested scope, e.g. a function.
Import the module at the top level to be able to use it throughout your code.

An alternative to importing the entire os module is to import only the
functions and constants that your code uses.

main.py
from os import path, environ BASE = '/user' # 👇️ /user/articles print(path.join(BASE, 'articles')) # 👇️ (venv) print(environ['VIRTUAL_ENV_PROMPT'])

The example shows how to import the path module and the environ mapping
object from the os module.

Instead of accessing the members on the module, e.g. os.environ, we now access
them directly.

This should be your preferred approach because it makes your code easier to
read.

For example, when we use an import such as import os, it is much harder to see which functions from the os module are being used in the file.

Conversely, when we import specific functions, it is much easier to see which
functions from the os module are being used.

The os module provides a portable way of using operating system dependent
functionality.

You can view all of the functions and constants the os module provides by
visiting the official docs.

Conclusion #

The Python “NameError: name ‘os’ is not defined” occurs when we use the os
module without importing it first. To solve the error, import the os module
before using it – import os.