操作文件
open
(file, mode=‘r‘, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Open file and return a corresponding file object. If the file cannot be opened, an OSError
is raised.
file is either a string or bytes object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd
False
.)
mode is an optional string that specifies the mode in which the file is opened. It defaults to ‘r‘
which means open for reading in text mode. Other common values are ‘w‘
for writing (truncating the file if it already exists), ‘x‘
for exclusive creation and ‘a‘
for appending (which on some
locale.getpreferredencoding(False)
is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encodingCharacter | Meaning |
---|---|
‘r‘ |
open for reading (default)。讀操作 |
‘w‘ |
open for writing, truncating the file first 打開文件進行寫操作,如果文件已經存在,會清空其內容 |
‘x‘ |
open for exclusive creation, failing if the file already exists python3.5 新增加的模式,獨占創建文件。如果文件已經存在,則創建失敗。 |
‘a‘ |
open for writing, appending to the end of the file if it exists 。打開文件進行寫操作。如果文件已經.存在,則在文件的末尾進行添加。 |
‘b‘ |
binary mode。二進制模式。 |
‘t‘ |
text mode (default) 文本模式 |
‘+‘ |
open a disk file for updating (reading and writing) 打開文件進行更新操作,也就是支持對文件進行讀寫操作。註意文件操作指針的位置。 read 和write操作都會移動當前文件的操作指針。例如write(‘haha‘),會覆蓋當前指針所在位置後面的4個位置,這時指針也移動了4個位置。 read操作同樣也會移動指針位置。 w+: 該模式依然是會在打開文件的同時清空文件的內容。請註意。
|
‘U‘ |
universal newlines mode (deprecated) |
操作文件