Latest web development tutorials

Python os.open () method

Python File (File) method Python OS file / directory methods


Outline

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

grammar

open () method syntax is as follows:

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

parameter

  • file - the file to open

  • flags - This parameter can be one option, multiple use "|" separated:

    • os.O_RDONLY: opened in read-only mode
    • os.O_WRONLY: opened in write-only
    • os.O_RDWR: opened in read and write
    • os.O_NONBLOCK: open without blocking
    • os.O_APPEND: Open in additional
    • os.O_CREAT: Create and open a new file
    • os.O_TRUNC: Open a file and truncate it to zero length (must have write permission)
    • os.O_EXCL: If the specified file exists, an error is returned
    • os.O_SHLOCK: automatically acquire a shared lock
    • os.O_EXLOCK: lock automatically obtain independent
    • os.O_DIRECT: eliminate or reduce the effect of caching
    • os.O_FSYNC: synchronous write
    • os.O_NOFOLLOW: Not Track soft links
  • mode - similar to the chmod () .

return value

Returns a new open file descriptors.

Examples

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

#!/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 above program output is:

关闭文件成功!!

Python File (File) method Python OS file / directory methods