Python language zero-based introductory tutorial (25)

Python OS file/directory methods

Python language zero-based introductory tutorial (24)

39. Python os.openpty() method

Overview
The os.openpty() method is used to open a new pseudo-terminal pair. Return the file descriptors for pty and tty.

Syntax
The syntax of the openpty() method is as follows:

os.openpty()

Parameters
No
return value
Returns the file descriptor pair, master and slave.

Example
The following example demonstrates the use of the openpty() method:

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

import os

# 主 pty, 从 tty
m,s = os.openpty()

print m
print s

# 显示终端名
s = os.ttyname(s)
print m
print s

The output of executing the above program is:

3
4
3
/dev/pty0

40. Python os.pathconf() method

Overview
The os.pathconf() method is used to return system configuration information for an open file.

Available under Unix platforms.

Syntax
The syntax of the fpathconf() method is as follows:

os.fpathconf(fd, name)

Parameter
name – file descriptor

name – the retrieved system configuration value, which may be a string defining the system value, these names are specified in many standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms also define some additional names. These names are in the pathconf_names dictionary on the host OS. For configuration variables not in pathconf_names, passing a number as the name is also acceptable.

Return Value
Returns the system information of the file.

Example
The following example demonstrates the use of the fpathconf() method:

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

import os, sys

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

print "%s" % os.pathconf_names

# 获取文件最大连接数
no = os.fpathconf(fd, 'PC_LINK_MAX')
print "Maximum number of links to the file. :%d" % no

# 获取文件名最大长度
no = os.fpathconf(fd, 'PC_NAME_MAX')
print "Maximum length of a filename :%d" % no

# 关闭文件
os.close( fd)

print "关闭文件成功!!"

The output of executing the above program is:

关闭文件成功!!

41. Python os. pipe() method

Overview
The os.pipe() method is used to create a pipe, returning a pair of file descriptors (r, w) for reading and writing respectively.

Syntax
The syntax of the pipe() method is as follows:

os.pipe()

parameter
none

Return Value
Returns a file descriptor pair.

Example
The following example demonstrates the use of the pipe() method:

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

import os, sys

print "The child will write text to a pipe and "
print "the parent will read the text written by child..."

# file descriptors r, w for reading and writing
r, w = os.pipe() 

processid = os.fork()
if processid:
    # This is the parent process 
    # Closes file descriptor w
    os.close(w)
    r = os.fdopen(r)
    print "Parent reading"
    str = r.read()
    print "text =", str   
    sys.exit(0)
else:
    # This is the child process
    os.close(r)
    w = os.fdopen(w, 'w')
    print "Child writing"
    w.write("Text written by child...")
    w.close()
    print "Child closing"
    sys.exit(0)

The output of executing the above program is:

The child will write text to a pipe and
the parent will read the text written by child...
Parent reading
Child writing
Child closing
text = Text written by child...

42. Python os. popen() method

Overview
The os.popen() method is used to open a pipe from a command.

Valid in Unix, Windows

Grammar
The syntax of the popen() method is as follows:

os.popen(command[, mode[, bufsize]])

Parameters
command – The command to use.

mode - mode permission can be 'r' (default) or 'w'.

bufsize - Specifies the buffer size required for the file: 0 means no buffering; 1 means line buffering; other positive values ​​mean using a buffer of the parameter size (approximate value, in bytes). Negative bufsize means to use the system's default value, generally speaking, for tty devices, it is line buffered; for other files, it is full buffered. If no parameter is changed, the default value of the system is used.

Return value
Returns an open file object whose file descriptor is fd

Example
The following example demonstrates the use of the popen() method:

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

import os, sys

# 使用 mkdir 命令
a = 'mkdir nwdir'

b = os.popen(a,'r',1)

print b

The output of executing the above program is:

open file 'mkdir nwdir', mode 'r' at 0x81614d0

43. Python os. read() method

Overview
The os.read() method is used to read up to n bytes from the file descriptor fd and return a string containing the read bytes. The file descriptor fd corresponds to the end of the file and returns an empty string.

Valid in Unix, Windows

Syntax
The syntax of the read() method is as follows:

os.read(fd,n)
parameter
fd – file descriptor.

n – the number of bytes read.

Return Value
Returns a string containing the read bytes

Example
The following example demonstrates the use of the read() method:

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

import os, sys
# 打开文件
fd = os.open("f1.txt",os.O_RDWR)
	
# 读取文本
ret = os.read(fd,12)
print ret

# 关闭文件
os.close(fd)
print "关闭文件成功!!"

The output of executing the above program is:

This is test
关闭文件成功!!

44. Python os. readlink() method

Overview
The os.readlink() method is used to return the file pointed to by the soft link. May return absolute or relative paths.

Valid in Unix

Syntax
The syntax of the readlink() method is as follows:

os.readlink(path)

Parameter
path – the soft link path to look for

Return value
Returns the file pointed to by the soft link

Example
The following example demonstrates the use of the readlink() method:

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

import os

src = '/usr/bin/python'
dst = '/tmp/python'

# 创建软链接
os.symlink(src, dst)

# 使用软链接显示源链接
path = os.readlink( dst )
print path

The output of executing the above program is:

/usr/bin/python

45. Python os. remove() method

Overview
The os.remove() method is used to delete the file at the specified path. If the specified path is a directory, OSError will be thrown.

This method is the same as unlink().

Available in Unix, Windows

Syntax
The syntax of the remove() method is as follows:

os.remove(path)

Parameter
path – the path of the file to remove

Return Value
The method has no return value

Example
The following example demonstrates the use of the remove() method:

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

import os, sys

# 列出目录
print "目录为: %s" %os.listdir(os.getcwd())

# 移除
os.remove("aa.txt")

# 移除后列出目录
print "移除后 : %s" %os.listdir(os.getcwd())

The output of executing the above program is:

目录为:
[ 'a1.txt','aa.txt','resume.doc' ]
移除后 : 
[ 'a1.txt','resume.doc' ]

46. ​​Python os.removedirs() method

Overview
The os.removedirs() method is used to remove directories recursively. Like rmdir() , removedirs() only tries their parent folders if subfolders are successfully removed, until an error is thrown (which is basically ignored, since it generally means your folder is not empty).

Syntax
The syntax of the removedirs() method is as follows:

os.removedirs(path)

Parameter
path – directory path to remove

Return Value
The method has no return value

Example
The following example demonstrates the use of the removedirs() method:

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

import os, sys

# 列出目录
print "目录为: %s" %os.listdir(os.getcwd())

# 移除
os.removedirs("/test")

# 列出移除后的目录
print "移除后目录为 %s :" %os.listdir(os.getcwd())

The output of executing the above program is:

目录为:
[  'a1.txt','resume.doc','a3.py','test' ]
移除后目录为:
[  'a1.txt','resume.doc','a3.py' ]

47. Python os.rename() method

Overview
The os.rename() method is used to rename a file or directory from src to dst, if dst is an existing directory, OSError will be thrown.

Grammar
The syntax of the rename() method is as follows:

os.rename(src, dst)

Parameters
src – the file or directory name to modify

dst – modified file or directory name

Return Value
The method has no return value

Example
The following example demonstrates the use of the rename() method:

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

import os, sys

# 列出目录
print "目录为: %s"%os.listdir(os.getcwd())

# 重命名
os.rename("test","test2")

print "重命名成功。"

# 列出重命名后的目录
print "目录为: %s" %os.listdir(os.getcwd())

The output of executing the above program is:

目录为:
[  'a1.txt','resume.doc','a3.py','test' ]
重命名成功。
[  'a1.txt','resume.doc','a3.py','test2' ]

48. Python os.renames() method

Overview
The os.renames() method is used to rename directories or files recursively. Similar to rename().

Syntax
The syntax of the renames() method is as follows:

os.renames(old, new)

parameter
old – the directory to rename

new -- the new name of the file or directory. It could even be a file contained in a directory, or a complete directory tree.

Return Value
The method has no return value

Example
The following example demonstrates the use of the renames() method:

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

import os, sys
print "当前目录为: %s" %os.getcwd()

# 列出目录
print "目录为: %s"%os.listdir(os.getcwd())

# 重命名 "aa1.txt"
os.renames("aa1.txt","newdir/aanew.txt")

print "重命名成功。"

# 列出重命名的文件 "aa1.txt"
print "目录为: %s" %os.listdir(os.getcwd())

The output of executing the above program is:

当前目录为: /tmp
目录为:
 [  'a1.txt','resume.doc','a3.py','aa1.txt','Administrator','amrood.admin' ]
重命名成功。
目录为:
 [  'a1.txt','resume.doc','a3.py','Administrator','amrood.admin' ]

49. Python os.rmdir() method

Overview
The os.rmdir() method is used to delete the directory of the specified path. Only if the folder is empty, otherwise, OSError is raised.

Syntax
The syntax of the rmdir() method is as follows:

os.rmdir(path)

Parameter
path – directory path to delete

Return Value
The method has no return value

Example
The following example demonstrates the use of the rmdir() method:

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

import os, sys

# 列出目录
print "目录为: %s"%os.listdir(os.getcwd())

# 删除路径
os.rmdir("mydir")

# 列出重命名后的目录
print "目录为: %s" %os.listdir(os.getcwd())

The output of executing the above program is:

目录为:
[  'a1.txt','resume.doc','a3.py','mydir' ]
目录为:
[  'a1.txt','resume.doc','a3.py' ]

50. Python os.stat() method

Overview
The os.stat() method is used to perform a system stat call on the given path.

Syntax
The syntax of the stat() method is as follows:

os.stat(path)

Parameter
path – specify the path

Return value
stat structure:

st_mode: inode protection mode
st_ino: inode node number.
st_dev: The device on which the inode resides.
st_nlink: The number of links of the inode.
st_uid: User ID of the owner.
st_gid: The owner's group ID.
st_size: size in bytes of normal files; contains data waiting for some special files.
st_atime: The time of last access.
st_mtime: The time of the last modification.
st_ctime: "ctime" as reported by the operating system. On some systems (such as Unix) it is the time of the latest metadata change, on others (such as Windows) it is the creation time (see your platform's documentation for details).

Example
The following example demonstrates the use of the stat() method:

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

import os, sys

# 显示文件 "a2.py" 信息
statinfo = os.stat('a2.py')

print statinfo

The output of executing the above program is:

posix.stat_result(st_mode=33188, st_ino=3940649674337682L, st_dev=277923425L, st
_nlink=1, st_uid=400, st_gid=401, st_size=335L, st_atime=1330498089, st_mtime=13
30498089, st_ctime=1330498089)

Guess you like

Origin blog.csdn.net/weixin_44006731/article/details/129103164