关于python

python内置函数open()用于打开文件和创建文件对象

语法

open(name[,mode[,bufsize]])

name:文件名

mode:指定文件的打开模式

  r:只读

  w:写入

  a:附加

  r+,w+,a+同时支持输入输出操作

  rb,wb+以二进制方式打开

bufsize:定义输出缓存

  0表示无输出缓存

  1表示使用缓冲

  负数表示使用系统默认设置

  正数表示使用近似指定大小的缓冲

#以只读方式打开text.txt文件,赋值给f1变量
>>> f1 = open(‘test.txt’,’r’)
#查看f1数据类型
>>> type(f1)

#读取文件内容,以字符串形式返回
>>> f1.read()
‘h1\nh2\nh3\nh4\nh5\nh6’
#此时指针处于文件末尾,通过tell获取当前指针位置,通过seek重新指定指针位置
>>> f1.readline()

>>> f1.tell()
>>> f1.seek(0)
#单行读取
>>> f1.readline()
‘h1\n’
#读取余下所有行,以列表方式返回
>>> f1.readlines()
[‘h2\n’, ‘h3\n’, ‘h4\n’, ‘h5\n’, ‘h6’]
#文件名
>>> f1.name
‘test.txt’
#关闭文件
>>> f1.close()
#文件写入
f2 = open(‘test.txt’,’w+’)
f2.write(‘hello’)
f2.close()
#向文件追加内容
f3 = open(‘test.txt’,’a’)
f3.write(‘hello’)
f3.close()
#通过flush,将缓冲区内容写入文件
#write将字符串值写入文件
f3 = open(‘test.txt’,’w+’)
for line in (i**2 for i in range(1,11)):
f3.write(str(line)+’\n’)
f3.flush()
#f3.close()
#writelines将列表值写入文件
f3 = open(‘test.txt’,’w+’)
lines = [’11’,’22’,’33’,’44’]
f3.writelines(lines)
f3.seek(0)
print(f3.readlines())
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 to locale.getpreferredencoding(false). |
| errors determines the strictness of encoding and decoding (see | help(codecs.codec) or the documentation for codecs.register) 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 | 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) from builtins.type | 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

*with

为了避免打开文件后忘记关闭,可以通过管理上下文,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

with open(“test.txt”,”a+”) as f:
f.write(“hello world!”)

以上就是关于python-open文件处理方法介绍的详细内容,更多请关注 第一php社区 其它相关文章!

Posted in 未分类

发表评论