Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python os.open() method

Python os.open() method

Python File methods Python OS file/directory methods


Overview

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

Syntax

The **open()** method syntax is as follows:


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

Parameters

- **os.O_RDONLY:** Open read-only - **os.O_WRONLY:** Open write-only - **os.O_RDWR :** Open for reading and writing - **os.O_NONBLOCK:** Do not block when opening - **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 (write permission required) - **os.O_EXCL:** Return an error if the specified file exists - **os.O_SHLOCK:** Acquire a shared lock automatically - **os.O_EXLOCK:** Acquire an exclusive lock automatically - **os.O_DIRECT:** Eliminate or reduce caching effects - **os.O_FSYNC :** Synchronous writes - **os.O_NOFOLLOW:** Do not follow symbolic links

Return Value

Returns the 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

# Open file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# Write string
os.write(fd, "This is test")

# Close file
os.close( fd )

print "关闭文件成功!!"

The output of the above program is:


关闭文件成功!!

Python File methods Python OS file/directory methods