Python os.open() Method

Python OS File/Directory Methods


Overview

The os.open() method is used to open a file and set the required opening options. The mode parameter is optional and defaults to 0777.

Syntax

open()The method syntax is as follows:

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

Parameters

  • file-- The file to open

  • flags-- This parameter can be the following options, separated by "|" when multiple are used:

    • os.O_RDONLY:Open in read-only mode
    • os.O_WRONLY:Open in write-only mode
    • os.O_RDWR :Open in read-write mode
    • os.O_NONBLOCK:Open without blocking
    • os.O_APPEND:Open in append mode
    • os.O_CREAT:Create and open a new file
    • os.O_TRUNC:Open a file and truncate its length to zero (must have write permission)
    • os.O_EXCL:Return an error if the specified file exists
    • os.O_SHLOCK:Automatically acquire a shared lock
    • os.O_EXLOCK:Automatically acquire an exclusive lock
    • os.O_DIRECT:Eliminate or reduce cache effects
    • os.O_FSYNC :Synchronous write
    • os.O_NOFOLLOW:Do not follow symbolic links
  • mode-- Similar tochmod()。

Return Value

Returns the file descriptor of the newly opened file.

Example

The following example demonstrates the use of the open() method:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os, sys

# 打开文件
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# 写入字符串
os.write(fd, "This is test")

# 关闭文件
os.close( fd )

print "关闭文件成功!!"

The output of the above program is:

File closed successfully!!

Python OS File/Directory Methods

Other Extensions