open() returns a file object, and is most commonly used with two arguments: "open(filename, mode)".
open() 返回一个文件,通常的用法需要两个参数: "open(filename, mode)"。
>>> f=open('/tmp/workfile', 'w') >>> print f <open file '/tmp/workfile', mode 'w' at 80a0960>
The first argument is a string containing the filename. The second
argument is another string containing a few characters describing the
way in which the file will be used. mode can be 'r'
when
the file will only be read, 'w'
for only writing (an existing
file with the same name will be erased), and 'a'
opens the file
for appending; any data written to the file is automatically added to
the end. 'r+'
opens the file for both reading and writing.
The mode argument is optional; 'r'
will be assumed if
it's omitted.
第一个参数是一个标识文件名的字符串。第二个参数是由有限的字母组成的字符串,描述了文件将会被如何使用。可选的
模式 有: 'r'
,此选项使文件只读; 'w'
,此选项使文件只写(对于同名文件,该操作使原有文件被覆盖);
'a'
,此选项以追加方式打开文件; 'r+'
,此选项以读写方式打开文件;如果没有指定,默认为 'r'
模式。
On Windows and the Macintosh, 'b'
appended to the
mode opens the file in binary mode, so there are also modes like
'rb'
, 'wb'
, and 'r+b'
. Windows makes a
distinction between text and binary files; the end-of-line characters
in text files are automatically altered slightly when data is read or
written. This behind-the-scenes modification to file data is fine for
ASCII text files, but it'll corrupt binary data like that in JPEGs or
.EXE files. Be very careful to use binary mode when reading and
writing such files. (Note that the precise semantics of text mode on
the Macintosh depends on the underlying C library being used.)
在Windows 和 Macintosh平台上, 'b'
模式以二进制方式打开文件,所以可能会有类似于 'rb'
,
'wb'
, 'r+b'
等等模式组合。
Windows平台上文本文件与二进制文件是有区别的,读写文本文件时,行尾会自动添加行结束符。这种后台操作方式对
ASCII 文本文件没有什么问题,但是操作 JPEG 或 .EXE
这样的二进制文件时就会产生破坏。在操作这些文件时一定要记得以二进制模式打开。(需要注意的是
Mactiontosh 平台上的文本模式依赖于其使用的底层C库)。