GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Tutorials
  • My W3Schools
  • W3Schools app iOS & Android NEW
  • Spaces
  • Get Certified
  • Plus
  • Practice
  • Campus (previously Academy)
  • Logout
  • 
  • 
  • 
  • 
  • Sign in

This view

  • Original page
  • New address

GeezerVison is showing www.w3schools.com — Python os Module

Menu
Search field
×
See More  
NEW W3Schools app iOS & Android Start the adventure
Sign In
★ +1 Spaces Upgrade Paid Courses Spaces Upgrade Paid Courses
   ❮     
     ❯   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

Python Tutorial

Python HOME Python Intro Python Get Started Python Syntax
Syntax Statements Code Challenge
Python Output
Print Text Print Numbers Code Challenge
Python Comments
Comments Code Challenge
Python Variables
Python Variables Variable Names Assign Multiple Values Output Variables Global Variables Variable Exercises Code Challenge
Python Data Types
Data Types Code Challenge
Python Numbers
Numbers Code Challenge
Python Casting
Casting Code Challenge
Python Strings
Python Strings Slicing Strings Modify Strings Concatenate Strings Format Strings Escape Characters String Methods String Exercises Code Challenge
Python Booleans
Booleans Code Challenge
Python Operators
Python Operators Arithmetic Operators Assignment Operators Ternary Operator Comparison Operators Logical Operators Identity Operators Membership Operators Bitwise Operators Operator Precedence Code Challenge
Python Lists
Python Lists Access List Items Change List Items Add List Items Remove List Items Loop Lists List Comprehension Sort Lists Copy Lists Join Lists List Methods List Exercises Code Challenge
Python Tuples
Python Tuples Access Tuples Update Tuples Unpack Tuples Loop Tuples Join Tuples Tuple Methods Tuple Exercises Code Challenge
Python Sets
Python Sets Access Set Items Add Set Items Remove Set Items Loop Sets Join Sets Frozenset Set Methods Set Exercises Code Challenge
Python Dictionaries
Python Dictionaries Access Items Change Items Add Items Remove Items Loop Dictionaries Copy Dictionaries Nested Dictionaries Dictionary Methods Dictionary Exercises Code Challenge
Python If...Else
Python If Python Elif Python Else Shorthand If Logical Operators Nested If Pass Statement Code Challenge
Python Match
Match Code Challenge
Python While Loops
While Loops Code Challenge
Python For Loops
For Loops Code Challenge
Python Functions
Python Functions Python Arguments Python *args / **kwargs Python Scope Python Decorators Python Lambda Python Recursion Python Generators Code Challenge
Python Range
Range Code Challenge
Python Arrays
Arrays Code Challenge
Python Iterators
Iterators Code Challenge
Python Modules
Modules Code Challenge
Python Dates
Dates Code Challenge
Python Math
Math Code Challenge
Python JSON
JSON Code Challenge
Python RegEx
RegEx Code Challenge
Python PIP Python Try...Except
Try...Except Code Challenge
Python String Formatting
String Formatting Code Challenge
Python None
None Code Challenge
Python User Input Python VirtualEnv

Python Classes

Python OOP Python Classes/Objects
Classes/Objects Code Challenge
Python __init__ Method
__init__ Method Code Challenge
Python self Parameter
self Parameter Code Challenge
Python Class Properties
Class Properties Code Challenge
Python Class Methods
Class Methods Code Challenge
Python Magic Methods
Magic Methods __str__ __repr__ __eq__ __add__ __len__ __lt__ __contains__ __call__ Code Challenge
Python Inheritance
Inheritance Code Challenge
Python Polymorphism
Polymorphism Code Challenge
Python Encapsulation
Encapsulation Code Challenge
Python Inner Classes

File Handling

Python File Handling Python Read Files Python Write/Create Files Python Delete Files

Python Modules

NumPy Tutorial Pandas Tutorial SciPy Tutorial Django Tutorial

Python Matplotlib

Matplotlib Intro Matplotlib Get Started Matplotlib Pyplot Matplotlib Plotting Matplotlib Markers Matplotlib Line Matplotlib Labels Matplotlib Grid Matplotlib Subplot Matplotlib Scatter Matplotlib Bars Matplotlib Histograms Matplotlib Pie Charts

Machine Learning

Getting Started Mean Median Mode Standard Deviation Percentile Data Distribution Normal Data Distribution Scatter Plot Linear Regression Polynomial Regression Multiple Regression Scale Train/Test Decision Tree Confusion Matrix Hierarchical Clustering Logistic Regression Grid Search Categorical Data K-means Bootstrap Aggregation Cross Validation AUC - ROC Curve K-nearest neighbors

Python DSA

Python DSA Lists and Arrays Stacks Queues Linked Lists Hash Tables Trees Binary Trees Binary Search Trees AVL Trees Graphs Linear Search Binary Search Bubble Sort Selection Sort Insertion Sort Quick Sort Counting Sort Radix Sort Merge Sort

Python MySQL

MySQL Get Started MySQL Create Database MySQL Create Table MySQL Insert MySQL Select MySQL Where MySQL Order By MySQL Delete MySQL Drop Table MySQL Update MySQL Limit MySQL Join

Python MongoDB

MongoDB Get Started MongoDB Create DB MongoDB Collection MongoDB Insert MongoDB Find MongoDB Query MongoDB Sort MongoDB Delete MongoDB Drop Collection MongoDB Update MongoDB Limit

Python Cert

Python Certificate

Python How To

Remove List Duplicates Reverse a String Add Two Numbers

Python Examples

Python Examples Python Videos Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training

Python Reference

Python Overview Python Built-in Functions
abs() all() any() ascii() bin() bool() bytearray() bytes() callable() chr() compile() complex() delattr() dict() dir() divmod() enumerate() eval() exec() filter() float() format() frozenset() getattr() globals() hasattr() hex() id() input() int() isinstance() issubclass() iter() len() list() locals() map() max() memoryview() min() next() object() oct() open() ord() pow() print() range() reversed() round() set() setattr() slice() sorted() str() sum() super() tuple() type() vars() zip()
Python String Methods
capitalize() casefold() center() count() encode() endswith() expandtabs() find() format() format_map() index() isalnum() isalpha() isascii() isdecimal() isdigit() isidentifier() islower() isnumeric() isprintable() isspace() istitle() isupper() join() ljust() lower() lstrip() maketrans() partition() replace() rfind() rindex() rjust() rpartition() rsplit() rstrip() split() splitlines() startswith() strip() swapcase() title() translate() upper() zfill()
Python List Methods
append() clear() copy() count() extend() index() insert() pop() remove() reverse() sort()
Python Dictionary Methods
clear() copy() fromkeys() get() items() keys() pop() popitem() setdefault() update() values()
Python Tuple Methods
count() index()
Python Set Methods
add() clear() copy() difference() difference_update() discard() intersection() intersection_update() isdisjoint() issubset() < issuperset() > pop() remove() symmetric_difference() symmetric_difference_update() union() update()
Python File Methods
close() fileno() flush() isatty() read() readable() readline() readlines() seek() seekable() tell() truncate() writable() write() writelines()
Python Keywords
and as assert async await break case class continue def del elif else except False finally for from global if import in is lambda match None nonlocal not or pass raise return True try while with yield
Python Exceptions
ArithmeticError AssertionError AttributeError Exception EOFError FloatingPointError GeneratorExit ImportError IndentationError IndexError KeyError KeyboardInterrupt LookupError MemoryError NameError NotImplementedError OSError OverflowError ReferenceError RuntimeError StopIteration SyntaxError TabError SystemError SystemExit TypeError UnboundLocalError UnicodeError UnicodeEncodeError UnicodeDecodeError UnicodeTranslateError ValueError ZeroDivisionError
Python Glossary

Module Reference

Built-in Modules
abc aifc argparse array ast asyncio atexit base64 bdb binascii bisect builtins bz2 calendar cgi cgitb cmd code codecs codeop collections colorsys concurrent configparser contextlib contextvars copy copyreg csv ctypes curses dataclasses datetime dbm decimal difflib dis doctest email encodings ensurepip enum errno faulthandler filecmp fileinput fnmatch fractions ftplib functools gc getopt getpass gettext glob graphlib gzip hashlib heapq hmac html http idlelib imaplib imghdr imp importlib inspect io json keyword linecache locale logging lzma mailbox mailcap marshal math mimetypes mmap modulefinder msilib msvcrt multiprocessing netrc nntplib numbers nis ntpath operator optparse os pathlib pdb pickle pickletools pipes pkgutil platform plistlib poplib posix pprint profile pstats pty pyclbr pydoc py_compile queue quopri random re reprlib resource rlcompleter runpy sched secrets select selectors shelve shlex shutil signal site smtplib socket socketserver sqlite3 ssl stat statistics string stringprep struct subprocess sunau symtable sys sysconfig tabnanny tarfile telnetlib tempfile termios test textwrap threading time timeit tkinter token tokenize tomllib trace traceback tracemalloc tty turtle types typing unicodedata unittest urllib uuid venv warnings wave weakref webbrowser wsgiref xdrlib xml xmlrpc zipapp zipfile zipimport zlib zoneinfo
Random Module
seed() getstate() setstate() getrandbits() randrange() randint() choice() choices() shuffle() sample() random() uniform() triangular()
Requests Module
delete(url, args) get(url, params, args) head(url, args) post(url, data, json, args)
Statistics Module
statistics.harmonic_mean() statistics.mean() statistics.median() statistics.median_grouped() statistics.median_high() statistics.median_low() statistics.mode() statistics.pstdev() statistics.stdev() statistics.pvariance() statistics.variance()
Math Module
math.acos() math.acosh() math.asin() math.asinh() math.atan() math.atan2() math.atanh() math.ceil() math.comb() math.copysign() math.cos() math.cosh() math.degrees() math.dist() math.erf() math.erfc() math.exp() math.expm1() math.fabs() math.factorial() math.floor() math.fmod() math.frexp() math.fsum() math.gamma() math.gcd() math.hypot() math.isclose() math.isfinite() math.isinf() math.isnan() math.isqrt() math.ldexp() math.lgamma() math.log() math.log10() math.log1p() math.log2() math.perm() math.pow() math.prod() math.radians() math.remainder() math.sin() math.sinh() math.sqrt() math.tan() math.tanh() math.trunc() math.e math.inf math.nan math.pi math.tau
cMath Module
cmath.acos(x) cmath.acosh(x) cmath.asin(x) cmath.asinh(x) cmath.atan(x) cmath.atanh(x) cmath.cos(x) cmath.cosh(x) cmath.exp(x) cmath.isclose() cmath.isfinite(x) cmath.isinf(x) cmath.isnan(x) cmath.log(x[, base]) cmath.log10(x) cmath.phase() cmath.polar() cmath.rect() cmath.sin(x) cmath.sinh(x) cmath.sqrt(x) cmath.tan(x) cmath.tanh(x) cmath.e cmath.inf cmath.infj cmath.nan cmath.nanj cmath.pi cmath.tau


Python os Module

❮ Previous Python Module Reference Next ❯

Example

Print the OS name (stable output):

import os

print(os.name)
Try it Yourself »

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

Use it to work with the filesystem, environment variables, processes, and more.


Share

Members

Notes:

[Windows] = Available on Windows only.

[Unix] = Available on POSIX systems (Linux, macOS, etc.).

[Linux] = Linux-only.

Some functions exist on multiple platforms but may have limited behavior (marked in the description).

Member Description
access()Check user's permissions for a path.
add_dll_directory() [Windows]Add a path to the DLL search path.
chdir()Change the current working directory.
chmod()Change the mode (permissions) of a path.
chown() [Unix]Change owner and group of path.
close()Close a file descriptor.
closerange()Close a range of file descriptors.
cpu_count()Return the number of CPUs in the system (may be None).
ctermid() [Unix]Return filename of controlling terminal.
devnullPath of the null device.
device_encoding()Return encoding for a file descriptor, or None.
dup()Duplicate a file descriptor.
dup2()Duplicate a file descriptor to a given fd.
dup3()Duplicate a file descriptor to a given fd (with flags).
environMapping object representing the process environment.
execl()Execute a new program (varargs form).
execle()Execute a new program with environment (varargs).
execlp()Execute a new program, searching PATH (varargs).
execlpe()Execute a new program with environment, searching PATH (varargs).
execv()Execute a new program, replacing the current process.
execve()Execute a new program with environment (low-level).
execvp()Execute a program, searching PATH.
execvpe()Execute a program with environment, searching PATH.
extsepExtension separator for the operating system.
fchdir() [Unix]Change working directory to the one given by an open file descriptor.
fchmod() [Unix]Change the mode of a file given by file descriptor.
fchown() [Unix]Change owner and group of a file given by file descriptor.
fdopen()Return an open file object connected to a file descriptor.
fork() [Unix]Fork a child process.
fsdecode()Decode a path-like or bytes object to str.
fsencode()Encode a path-like or str object to bytes.
fspath()Return the file system representation of a path-like object.
fstat()Perform a stat on an open file descriptor.
ftruncate()Truncate a file to a specified length.
get_blocking()Get the blocking mode of a file descriptor.
getcwd()Return the current working directory as str.
getcwdb()Return the current working directory as bytes.
getegid() [Unix]Return the effective group id.
geteuid() [Unix]Return the effective user id.
get_exec_path()Return the sequence of directories that will be searched for executables.
getgid() [Unix]Return the real group id.
getgrouplist() [Unix]Return list of group ids a user belongs to.
get_inheritable()Get the inheritable flag of a file descriptor.
getlogin() [Unix]Return the name of the user logged in on the controlling terminal.
getpgid() [Unix]Return the process group id of a process.
getpgrp() [Unix]Return the process group id of the current process.
getpid()Return the current process id.
getppid()Return the parent process id.
getpriority() [Unix]Get process scheduling priority.
getsid() [Unix]Return the session id of a process.
get_terminal_size()Return the size of the terminal window as columns and lines.
getuid() [Unix]Return the real user id.
isatty()Return True if the file descriptor is open and connected to a tty device.
kill() [limited on Windows]Send signal to a process.
killpg() [Unix]Send a signal to a process group.
linesepString used to separate (or terminate) lines on the current platform.
link()Create a hard link pointing to a path.
listdir()Return a list of entries in a directory.
lseek()Set the position of a file descriptor.
lstat()Like stat(), but do not follow symbolic links.
makedirs()Recursively create directories.
memfd_create() [Linux]Create an anonymous memory file.
mkdir()Create a directory.
mkfifo() [Unix]Create a FIFO (named pipe).
mknod() [Unix]Create a filesystem node.
nameThe name of the OS-dependent module imported.
open()Low-level OS open; returns a file descriptor.
openpty() [Unix]Open a new pseudo-terminal pair.
pathSubmodule for pathname manipulations.
pathsepString used to separate search path components (e.g., ';' on Windows).
pipe()Create a pipe, returning a pair of file descriptors (r, w).
pipe2() [Unix]Create a pipe with flags.
posix_spawn() [Unix]Spawn a process (POSIX, efficient).
posix_spawnp() [Unix]Spawn a process searching PATH (POSIX).
pread() [Unix]Read from a file descriptor at a given position.
pwrite() [Unix]Write to a file descriptor at a given position.
putenv()Set the value of an environment variable.
read()Read from a file descriptor.
readlink()Return the path to which a symbolic link points.
readv() [Unix]Read from a file descriptor into multiple buffers.
register_at_fork() [Unix]Register callables to be executed at process fork.
remove()Remove (delete) a file.
rename()Rename a file or directory.
renames()Recursively rename a file or directory.
rmdir()Remove (delete) a directory.
scandir()Return an iterator of DirEntry objects.
sched_getaffinity() [Unix]Get CPU affinity mask.
sched_setaffinity() [Unix]Set CPU affinity mask.
sched_yield() [Unix]Yield the processor.
sepPath separator for the current platform.
set_blocking()Set the blocking mode of a file descriptor.
setegid() [Unix]Set the effective group id.
setenv()Set an environment variable (if available).
seteuid() [Unix]Set the effective user id.
setgid() [Unix]Set the real group id.
setgroups() [Unix]Set the list of group ids for the current process.
set_handle_inheritable() [Windows]Set handle inheritable flag.
set_inheritable()Set the inheritable flag of a file descriptor.
setpgid() [Unix]Set the process group id.
setpgrp() [Unix]Make the current process a session leader.
setpriority() [Unix]Set process scheduling priority.
setregid() [Unix]Set the real and effective group ids.
setreuid() [Unix]Set the real and effective user ids.
setsid() [Unix]Start a new session.
setuid() [Unix]Set the real user id.
spawnl()Spawn a process with a path (varargs).
spawnle()Spawn a process with a path and environment (varargs).
spawnlp()Spawn a process searching PATH (varargs).
spawnlpe()Spawn a process searching PATH with environment (varargs).
spawnv()Spawn a process with a path (vector args).
spawnve()Spawn a process with a path and environment (vector args).
spawnvp()Spawn a process searching PATH (vector args).
spawnvpe()Spawn a process searching PATH with environment (vector args).
startfile() [Windows]Open a file with its associated application.
stat()Perform a stat system call on a path.
statvfs() [Unix]Return filesystem statistics.
strerror()Return the error message corresponding to an errno value.
supports_bytes_environTrue if environ accepts bytes keys/values.
supports_dir_fdTrue if functions accept a dir_fd parameter.
supports_effective_idsTrue if functions support effective ids.
supports_fdTrue if functions accept a file descriptor.
supports_follow_symlinksTrue if functions support follow_symlinks parameter.
symlink()Create a symbolic link. On Windows, requires Developer Mode or administrator privileges.
sync() [Unix]Flush file system buffers.
system()Execute the command (string) in a subshell.
times()Return process times.
truncate()Truncate a file to a specified length.
umask()Set the process umask and return the previous value.
uname() [Unix]Return OS identification.
unlink()Remove (delete) a file.
urandom()Return random bytes for cryptographic use.
utime()Set access and modified times.
wait() [Unix]Wait for completion of a child process.
wait3() [Unix]Wait for a child process, returning resource usage.
wait4() [Unix]Wait for a child process with rusage.
waitpid() [Unix]Wait for completion of a specific child process.
walk()Generate file names in a directory tree by walking.
write()Write to a file descriptor.
writev() [Unix]Write to a file descriptor from multiple buffers.


❮ Previous Python Module Reference Next ❯
★ +1
Sign in to track progress
W3Schools Full Access - your next career move

REMOVE ADS

This way to the W3Schools Adventure app
Learn more about Adventure Mode›

Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —
Sign in to track progress

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

PLUS
SPACES
GET CERTIFIED
FOR TEACHERS
PRACTICE
CONTACT US
×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
AngularJS Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
   
FORUM ABOUT CAMPUS
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.









You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.