Python3 Os File Methods
# Python3 OS File/Directory Methods
## Python3.x Python3 OS File/Directory Methods
The `os` module is an important module in the Python standard library that provides functionality for interacting with the operating system.
Through the `os` module, you can perform tasks such as file operations, directory operations, environment variable management, and process management.
The `os` module is cross-platform, meaning you can use the same code on different operating systems (like Windows, Linux, macOS).
Before using the `os` module, you need to import it first. The code to import the `os` module is as follows:
```python
import os
* * *
### 1. Get Current Working Directory
The `os.getcwd()` function is used to get the path of the current working directory. The current working directory is the directory where the Python script is executed.
## Example
```python
current_directory = os.getcwd()
print("Current working directory:", current_directory)
### 2. Change Current Working Directory
The `os.chdir(path)` function is used to change the current working directory. `path` is the directory path you want to switch to.
## Example
```python
os.chdir("/path/to/new/directory")
print("New working directory:", os.getcwd())
### 3. List Directory Contents
The `os.listdir(path)` function is used to list all files and subdirectories in the specified directory. If the `path` parameter is not provided, it defaults to listing the contents of the current working directory.
## Example
```python
files_and_dirs = os.listdir()
print("Directory contents:", files_and_dirs)
### 4. Create Directory
The `os.mkdir(path)` function is used to create a new directory. If the directory already exists, it raises a `FileExistsError` exception.
## Example
```python
os.mkdir("new_directory")
### 5. Remove Directory
The `os.rmdir(path)` function is used to remove an empty directory. If the directory is not empty, it raises an `OSError` exception.
## Example
```python
os.rmdir("new_directory")
### 6. Remove File
The `os.remove(path)` function is used to delete a file. If the file does not exist, it raises a `FileNotFoundError` exception.
## Example
```python
os.remove("file_to_delete.txt")
### 7. Rename File or Directory
The `os.rename(src, dst)` function is used to rename a file or directory. `src` is the original path, and `dst` is the new path.
## Example
```python
os.rename("old_name.txt", "new_name.txt")
### 8. Get Environment Variable
The `os.getenv(key)` function is used to get the value of a specified environment variable. If the environment variable does not exist, it returns `None`.
## Example
```python
home_directory = os.getenv("HOME")
print("HOME directory:", home_directory)
### 9. Execute System Command
The `os.system(command)` function is used to execute a command in the operating system's shell. After the command is executed, it returns the exit status of the command.
## Example
```python
os.system("ls -l")
## Common OS Methods
The **os** module provides a very rich set of methods for handling files and directories. Common methods are shown in the table below:
| No. | Method and Description |
| --- | --- |
| 1 | [os.access(path, mode)](#) Test a file's accessibility mode |
| 2 | [os.chdir(path)](#) Change the current working directory |
| 3 | [os.chflags(path, flags)](#) Set the flags of path to a numeric value. |
| 4 | [os.chmod(path, mode)](#) Change the permissions of a path |
| 5 | [os.chown(path, uid, gid)](#) Change the owner and group id of path |
| 6 | [os.chroot(path)](#) Change the root directory of the current process |
| 7 | [os.close(fd)](#) Close file descriptor fd |
| 8 | [os.closerange(fd_low, fd_high)](#) Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring errors |
| 9 | [os.dup(fd)](#) Duplicate file descriptor fd |
| 10 | [os.dup2(fd, fd2)](#) Duplicate file descriptor fd to fd2 |
| 11 | [os.fchdir(fd)](#) Change the current working directory relative to a file descriptor |
| 12 | [os.fchmod(fd, mode)](#) Change the mode of the file specified by a file descriptor to the numeric mode. |
| 13 | [os.fchown(fd, uid, gid)](#) Change the owner and group id of the file specified by file descriptor fd. |
| 14 | [os.fdatasync(fd)](#) Force write of file with file descriptor fd to disk, but do not force update of file status information. |
| 15 | [os.fdopen(fd[, mode[, bufsize]])](#) Return a file object connected to the file descriptor fd. |
| 16 | [os.fpathconf(fd, name)](#) Return system configuration information relevant to an open file. name specifies the configuration value to retrieve; it may be a string which is the name of a defined value, these names are specified in a number of standards (POSIX.1, Unix 95, Unix 98, and others). |
| 17 | [os.fstat(fd)](#) Return status for file descriptor fd, like stat(). |
| 18 | [os.fstatvfs(fd)](#) Return information about the filesystem containing the file associated with file descriptor fd, like statvfs(). Python 3.3 Equivalent to statvfs(). |
| 19 | [os.fsync(fd)](#) Force write of the file with file descriptor fd to disk. |
| 20 | [os.ftruncate(fd, length)](#) Truncate the file corresponding to file descriptor fd, so that it is at most length bytes in size. |
| 21 | [os.getcwd()](#) Return a string representing the current working directory |
| 22 | [os.getcwdb()](#) Return a bytes object representing the current working directory |
| 23 | [os.isatty(fd)](#) Return True if the file descriptor fd is open and connected to a tty(-like) device, else False. |
| 24 | [os.lchflags(path, flags)](#) Set the flags of path to a numeric value, like chflags(), but do not follow symbolic links. |
| 25 | [os.lchmod(path, mode)](#) Change the mode of a symbolic link. |
| 26 | [os.lchown(path, uid, gid)](#) Change the owner and group id of path similar to chown(), but do not follow symbolic links. |
| 27 | [os.link(src, dst)](#) Create a hard link pointing to src named dst. |
| 28 | [os.listdir(path)](#) Return a list containing the names of the entries in the directory given by path. |
| 29 | [os.lseek(fd, pos, how)](#) Set the current position of file descriptor fd to position pos, modified by how: SEEK_SET or 0 sets the position relative to the beginning of the file; SEEK_CUR or 1 sets the position relative to the current position; SEEK_END or 2 sets the position relative to the end of the file. |
| 30 | [os.lstat(path)](#) Like stat(), but do not follow symbolic links. |
| 31 | [os.major(device)](#) Extract the device major number from a raw device number (useful if you extracted the major number from the st_dev or st_rdev field of stat). |
| 32 | [os.makedev(major, minor)](#) Compose a raw device number from the major and minor device numbers. |
| 33 | [os.makedirs(path[, mode])](#) Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. |
| 34 | [os.minor(device)](#) Extract the device minor number from a raw device number (useful if you extracted the minor number from the st_dev or st_rdev field of stat). |
| 35 | [os.mkdir(path[, mode])](#) Create a directory named path with numeric mode mode. The default mode is 0777 (octal). |
| 36 | [os.mkfifo(path[, mode])](#) Create a FIFO (a named pipe) named path with numeric mode mode. The default mode is 0666 (octal). |
| 37 | [os.mknod(filename[, mode=0600, device])](#) Create a filesystem node (file, device special file, or named pipe) named filename. |
| 38 | [os.open(file, flags[, mode])](#) Open a file, setting various flags according to flags and possibly its mode according to mode. |
| 39 | [os.openpty()](#) Open a new pseudo-terminal pair. Return a pair of file descriptors (r, w) for the pty and the tty, respectively. |
| 40 | [os.pathconf(path, name)](#) Return system configuration information relevant to a named file. |
| 41 | [os.pipe()](#) Create a pipe. Return a pair of file descriptors (r, w) usable for reading and writing, respectively. |
| 42 | [os.popen(command[, mode[, bufsize]])](#) Open a pipe to command. |
| 43 | [os.read(fd, n)](#) Read at most n bytes from file descriptor fd. Return a bytes object containing the bytes read. If the end of the file referred to by fd has been reached, an empty bytes object is returned. |
| 44 | [os.readlink(path)](#) Return a string representing the path to which the symbolic link points. |
| 45 | [os.remove(path)](#) Remove (delete) the file path. If path is a directory, OSError is raised; see rmdir() below to remove a directory. |
| 46 | [os.removedirs(path)](#) Remove directories recursively. |
| 47 | [os.rename(src, dst)](#) Rename the file or directory src to dst. |
| 48 | [os.renames(old, new)](#) Recursive renaming or file moving function. Works like rename(), except creation of any intermediate directories needed to make the new pathname is done first. |
| 49 | [os.rmdir(path)](#) Remove (delete) the directory path. Only works when the directory is empty, otherwise, OSError is raised. |
| 50 | [os.stat(path)](#) Get the status of a file or a file descriptor. The return value is an object whose attributes correspond to the members of the stat structure, as returned by stat() system call. |
| 51 | [os.stat_float_times()](#) Determine whether stat_result represents time stamps as float objects. |
| 52 | [os.statvfs(path)](#) Get the filesystem statistics for a given path. |
| 53 | [os.symlink(src, dst)](#) Create a symbolic link pointing to src named dst. |
| 54 | [os.tcgetpgrp(fd)](#) Return the process group associated with the terminal file descriptor fd (which must be opened; see os.open()). |
| 55 | [os.tcsetpgrp(fd, pg)](#) Set the process group associated with the terminal file descriptor fd to pg. |
| 56 | os.tempnam([dir[, prefix]]) **Removed in Python3.** Return a unique pathname for creating a temporary file. |
| 57 | os.tmpfile() **Removed in Python3.** Return a new file object opened in mode 'w+b'. This file has no directory entries for it, and no file descriptor will be retained. It will be deleted automatically. |
| 58 | os.tmpnam() **Removed in Python3.** Return a unique pathname for creating a temporary file. |
| 59 | [os.ttyname(fd)](#) Return a string which specifies the terminal device associated with file descriptor fd. If fd is not associated with a terminal device, an exception is raised. |
| 60 | [os.unlink(path)](#) Remove (delete) the file path. |
| 61 | [os.utime(path, times)](#) Set the access and modified times of the file specified by path. |
| 62 | [os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])](#) Generate the file names in a directory tree by walking the tree either top-down or bottom-up. |
| 63 | [os.write(fd, str)](#) Write the bytestring in str to file descriptor fd. Return the number of bytes actually written. |
| 64 | [os.path module](#) Get file attribute information. |
| 65 | [os.pardir()](#) Get the parent directory of the current directory, displayed as a string. |
| 66 | [os.replace()](#) Rename a file or directory. |
| 67 | [os.startfile()](#) Used to open a file or folder on Windows. |
YouTip