Python Tutorials - Herong's Tutorial Examples
∟"sys" and "os" Modules
∟Use "os" Module to Manage Files
This section describes methods from the 'os' module for managing files.
"os" module also offers a number of methods
to perform read and write operations on files:
- os.close(fd) - Method closes the given file descriptor.
- os.fsync(fd) - Method forces any cached content to the storage associated to
the given file descriptor.
- os.ftruncate(fd, length) - Method truncates the content to "length" bytes associated to
the given file descriptor.
- os.lseek(fd, pos, how) - Method moves the current position to the given position
in the content associated to
the given file descriptor.
- os.mkdir(path) - Method creates a directory for the given path.
- os.open(path, flags) - Method opens a file of the given path and returns
a file descriptor.
- os.read(fd, n) - Method reads "n" bytes from
the given file descriptor.
- os.remove(path) - Method removes the file of the given path.
- os.rename(old, new) - Method renames the name of a file to a new name.
- os.rmdir(path) - Method removes an empty directory of the given path.
- os.scandir(path) - Method returns an iterator for files and sub-directories of the given path.
- os.stat(path) - Method returns status information of the given path.
- os.write(fd, data) - Method writes "data" to
the given file descriptor and returns the number of bytes written.
Here are examples on how to use above "os" methods.
>>> import os
# Loop through child items of a directory
>>> for child in os.scandir('docs'): child
...
<DirEntry 'conf.py'>
<DirEntry '_templates'>
<DirEntry 'make.bat'>
<DirEntry 'index.rst'>
<DirEntry '_build'>
<DirEntry '_static'>
<DirEntry 'Makefile'>
# write data, rename and read data on a file.
>>> fd = os.open('foo', os.O_CREAT|os.O_WRONLY)
>>> os.write(fd, b'some text')
9
>>> os.close(fd)
>>> os.rename('foo', 'bar')
>>> fd = os.open('bar', os.O_RDONLY)
>>> os.read(fd, 80)
b'some text'
>>> os.close(fd)
Table of Contents
About This Book
Running Python Code Online
Python on macOS Computers
Python on Linux Computers
Built-in Data Types
Variables, Operations and Expressions
Statements - Execution Units
Function Statement and Function Call
Iterators and Generators
List, Set and Dictionary Comprehensions
Classes and Instances
Modules and Module Files
Packages and Package Directories
►"sys" and "os" Modules
What Is "sys" Module
What Is "os" Module
Use "os" Module to Create Child Processes
►Use "os" Module to Manage Files
"pathlib" - Object-Oriented Filesystem Paths
"pip" - Package Installer for Python
SciPy.org - Python Libraries for Science
pandas - Data Analysis and Manipulation
Anaconda - Python Environment Manager
Jupyter Notebook and JupyterLab
References
Full Version in PDF/EPUB