Python - OS File/Directory Methods


The os module provides a big range of useful methods to manipulate files. Most of the useful methods are listed here −

Sr.No. Methods with Description

1

os.close(fd)

Close file descriptor fd.

2

os.closerange(fd_low, fd_high)

Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring errors.

3

os.dup(fd)

Return a duplicate of file descriptor fd.

4

os.fdatasync(fd)

Force write of file with filedescriptor fd to disk.

5

os.fdopen(fd[, mode[, bufsize]])

Return an open file object connected to the file descriptor fd.

6

os.fsync(fd)

Force write of file with filedescriptor fd to disk.

7

os.ftruncate(fd, length)

Truncate the file corresponding to file descriptor fd, so that it is at most length bytes in size.

8

os.lseek(fd, pos, how)

Set the current position of file descriptor fd to position pos, modified by how.

9

os.open(file, flags[, mode])

Open the file file and set various flags according to flags and possibly its mode according to mode.

10

os.read(fd, n)

Read at most n bytes from file descriptor fd. Return a string containing the bytes read. If the end of the file referred to by fd has been reached, an empty string is returned.

11

os.tmpfile()

Return a new file object opened in update mode (w+b).

12

os.write(fd, str)

Write the string str to file descriptor fd. Return the number of bytes actually written.

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements