python-open⽂件处理python内置函数open()⽤于打开⽂件和创建⽂件对象
语法
open(name[,mode[,bufsize]])
name:⽂件名
mode:指定⽂件的打开模式
r:只读
w:写⼊
a:附加
r+,w+,a+同时⽀持输⼊输出操作
rb,wb+以⼆进制⽅式打开
bufsize:定义输出缓存
0表⽰⽆输出缓存
1表⽰使⽤缓冲
负数表⽰使⽤系统默认设置
正数表⽰使⽤近似指定⼤⼩的缓冲
#以只读⽅式打开⽂件,赋值给f1变量
>>> f1 = open('','r')
#查看f1数据类型
>>> type(f1)
<class'_io.TextIOWrapper'>
#读取⽂件内容,以字符串形式返回
>>> f1.read()
'h1\nh2\nh3\nh4\nh5\nh6'
#此时指针处于⽂件末尾,通过tell获取当前指针位置,通过seek重新指定指针位置
>>> f1.readline()
''
>>> f1.tell()
22
>>> f1.seek(0)
#单⾏读取
>>> f1.readline()
'h1\n'
#读取余下所有⾏,以列表⽅式返回
>>> f1.readlines()
['h2\n', 'h3\n', 'h4\n', 'h5\n', 'h6']
#⽂件名
>>> f1.name
''
#关闭⽂件
>>> f1.close()
#⽂件写⼊
f2 = open('','w+')
f2.write('hello')
f2.close()
#向⽂件追加内容
f3 = open('','a')
f3.write('hello')
f3.close()
#通过flush,将缓冲区内容写⼊⽂件
#write将字符串值写⼊⽂件
f3 = open('','w+')
for line in (i**2 for i in range(1,11)):
f3.write(str(line)+'\n')
f3.flush()
#f3.close()
#writelines将列表值写⼊⽂件
f3 = open('','w+')
lines = ['11','22','33','44']
f3.writelines(lines)
f3.seek(0)
adlines())
f3.close()
#执⾏结果:['11223344']
>>> f3.closed
True
>>> f3.mode
'w+'
>>> f3.encoding
'cp936'
Help on TextIOWrapper object:
class TextIOWrapper(_TextIOBase)
| Character and line based layer over a BufferedIOBase object, buffer.
|
| encoding gives the name of the encoding that the stream will be
| decoded or encoded with. It defaults preferredencoding(False). |
| errors determines the strictness of encoding and decoding (see
| help(codecs.Codec) or the documentation ister) and
| defaults to "strict".
|
| newline controls how line endings are handled. It can be None, '',
| '\n', '\r', and'\r\n'. It works as follows:
|
| * On input, if newline is None, universal newlines mode is
| enabled. Lines in the input can end in'\n', '\r', or'\r\n', and
| these are translated into '\n' before being returned to the
| caller. If it is'', universal newline mode is enabled, but line
| endings are returned to the caller untranslated. If it has any of
| the other legal values, input lines are only terminated by the given
| string, and the line ending is returned to the caller untranslated.
|
| * On output, if newline is None, any '\n' characters written are
| translated to the system default line separator, os.linesep. If
| newline is''or'\n', no translation takes place. If newline is any
| of the other legal values, any '\n' characters written are translated
| to the given string.
|
| If line_buffering is True, a call to flush is implied when a call to
writelines()方法将什么写入文件| write contains a newline character.
|
| Method resolution order:
| TextIOWrapper
| _TextIOBase
| _IOBase
| builtins.object
|
| Methods defined here:
|
| __getstate__(...)
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __new__(*args, **kwargs) pe
| Create and return a new object. See help(type) for accurate signature. |
| __next__(self, /)
| Implement next(self).
|
| __repr__(self, /)
| Return repr(self).
|
| close(self, /)
| Flush and close the IO object.
|
| This method has no effect if the file is already closed.
|
| detach(self, /)
| Separate the underlying buffer from the TextIOBase and return it.
|
| After the underlying buffer has been detached, the TextIO is in an
| unusable state.
|
| fileno(self, /)
| Returns underlying file descriptor if one exists.
|
| OSError is raised if the IO object does not use a file descriptor.
|
| flush(self, /)
| Flush write buffers, if applicable.
|
| This is not implemented for read-only and non-blocking streams.
|
| isatty(self, /)
| Return whether this is an 'interactive' stream.
|
| Return False if it can't be determined.
|
| read(self, size=-1, /)
| Read at most n characters from stream.
|
| Read from underlying buffer until we have n characters or we hit EOF. | If n is negative or omitted, read until EOF.
|
| readable(self, /)
| Return whether object was opened for reading.
|
| If False, read() will raise OSError.
|
| readline(self, size=-1, /)
| Read until newline or EOF.
|
| Returns an empty string if EOF is hit immediately.
|
| seek(self, cookie, whence=0, /)
| Change stream position.
|
| Change the stream position to the given byte offset. The offset is
| interpreted relative to the position indicated by whence. Values
| for whence are:
|
| * 0 -- start of stream (the default); offset should be zero or positive
| * 1 -- current stream position; offset may be negative
| * 2 -- end of stream; offset is usually negative
|
| Return the new absolute position.
|
| seekable(self, /)
| Return whether object supports random access.
|
| If False, seek(), tell() and truncate() will raise OSError.
| This method may need to do a test seek().
|
| tell(self, /)
| Return current stream position.
|
| truncate(self, pos=None, /)
| Truncate file to size bytes.
|
| File pointer is left unchanged. Size defaults to the current IO
| position as reported by tell(). Returns the new size.
|
| writable(self, /)
| Return whether object was opened for writing.
|
| If False, write() will raise OSError.
|
| write(self, text, /)
| Write string to stream.
| Returns the number of characters written (which is always equal to
| the length of the string).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| buffer
|
| closed
|
| encoding
| Encoding of the text stream.
|
| Subclasses should override.
|
| errors
| The error setting of the decoder or encoder.
|
| Subclasses should override.
|
| line_buffering
|
| name
|
| newlines
| Line endings translated so far.
|
| Only line endings translated during reading are considered.
|
| Subclasses should override.
|
| ----------------------------------------------------------------------
| Methods inherited from _IOBase:
|
| __del__(...)
|
| __enter__(...)
|
| __exit__(...)
|
| __iter__(self, /)
| Implement iter(self).
|
| readlines(self, hint=-1, /)
| Return a list of lines from the stream.
|
| hint can be specified to control the number of lines read: no more
| lines will be read if the total size (in bytes/characters) of all
| lines so far exceeds hint.
|
| writelines(self, lines, /)
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _IOBase:
|
| __dict__
View Code
*with
为了避免打开⽂件后忘记关闭,可以通过管理上下⽂,当with代码块执⾏完毕时,内部会⾃动关闭并释放⽂件资源。with open("","a+") as f:
f.write("hello world!")
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论