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)
<class '_io.TextIOWrapper'> #读取文件内容,以字符串形式返回
>>> f1.read()
'h1\nh2\nh3\nh4\nh5\nh6' #此时指针处于文件末尾,通过tell获取当前指针位置,通过seek重新指定指针位置
>>> f1.readline()
''
>>> f1.tell()
22 >>> f1.seek(0)
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 = ['','','','']
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文件处理的更多相关文章

  1. Python读写文件

    Python读写文件1.open使用open打开文件后一定要记得调用文件对象的close()方法.比如可以用try/finally语句来确保最后能关闭文件. file_object = open('t ...

  2. python计算文件的md5值

    前言 最近要开发一个基于python的合并文件夹/目录的程序,本来的想法是基于修改时间的比较,即判断文件有没有改变,比较两个文件的修改时间即可.这个想法在windows的pc端下测试没有问题. 但是当 ...

  3. python操作文件案例二则

    前言 python 对于文件及文件夹的操作. 涉及到 遍历文件夹下所有文件 ,文件的读写和操作 等等. 代码一 作用:查找文件夹下(包括子文件夹)下所有文件的名字,找出 名字中含有中文或者空格的文件 ...

  4. Python :open文件操作,配合read()使用!

    python:open/文件操作 open/文件操作f=open('/tmp/hello','w') #open(路径+文件名,读写模式) 如何打开文件 handle=open(file_name,a ...

  5. python学习 文件操作

    一.python打开文件 #=====================python 文件打开方式 open()===================== # open(fileName,type) t ...

  6. Python之文件读写

    本节内容: I/O操作概述 文件读写实现原理与操作步骤 文件打开模式 Python文件操作步骤示例 Python文件读取相关方法 文件读写与字符编码 一.I/O操作概述 I/O在计算机中是指Input ...

  7. python 遍历文件夹 文件

    python 遍历文件夹 文件   import os import os.path rootdir = "d:\data" # 指明被遍历的文件夹 for parent,dirn ...

  8. python检测文件的MD5值

    python检测文件的MD5值MD5(单向散列算法)的全称是Message-Digest Algorithm 5(信息-摘要算法),经MD2.MD3和MD4发展而来.MD5算法的使用不需要支付任何版权 ...

  9. Python编码/文件读取/多线程

    Python编码/文件读取/多线程 个人笔记~~记录才有成长   编码/文件读取/多线程 编码 常用的一般是gbk.utf-8,而在python中字符串一般是用Unicode来操作,这样才能按照单个字 ...

  10. python 读写文件和设置文件的字符编码

    一. python打开文件代码如下: f = open("d:\test.txt", "w") 说明:第一个参数是文件名称,包括路径:第二个参数是打开的模式mo ...

随机推荐

  1. linux NFS 配置步骤

    转载 http://woxihuanpes.blog.163.com/blog/static/12423219820097139145238/ NFS server可以看作是一个FILE SERVER ...

  2. thinkphp - 复合查询(or、and 联合使用的方法)

    条件:查询今天内邮箱和QQ其中一项都不为空的有效数据的查询 释义:(or 条件)email  不为空 或者 qq_no 不为空    (and 条件) is_deleted 为0 并且 create_ ...

  3. 企业应用开发模式 ERP项目中应用到的技术和工具

    一.基础技术选型 C# .NET 3.5/4.0  这两个版本的.NET已经相当方便(Linq, Lambda,Parallel),语法简洁,配合WCF和WF两项技术,可以满足快速开发,维护方便的目标 ...

  4. CSS3与页面布局学习总结(三)——BFC、定位、浮动、7种垂直居中方法

    一.BFC与IFC 1.1.BFC与IFC概要 BFC(Block Formatting Context)即“块级格式化上下文”, IFC(Inline Formatting Context)即行内格 ...

  5. 学习SpringMVC——拦截器

    拦截器,顾名思义就是用来拦截的. 那什么是拦截,又为什么要拦截.对于Spring MVC来说,拦截器主要的工作对象就是用户的请求,拦截下来之后,我们可以在拦截的各个阶段悉心呵护[为所欲为].常见的比如 ...

  6. Django--自定义用户认证

    Django自带的用户认证 以前都是用Django自带的用户认证,用户名字段一对一关系对应Django--User表(其实它也是继承了abstractbaseuser). 1 2 3 from dja ...

  7. EF Code First学习系列

    EF Model First在实际工作中基本用不到,前段时间学了一下,大概的了解一下.现在开始学习Code First这种方式.这也是在实际工作中用到最多的方式. 下面先给出一些目录: 1.什么是Co ...

  8. 基于NodeJS的秘室聊天室

    借着放假期间将NodeJS重新回顾了一下并玩了一下sketch来进行设计界面,很不错.(注:代码整理后会放到github上,请关注.) 本次聊天室我给它定义了一个名称叫“秘密聊天室”. 需求: 技术选 ...

  9. C#解决界面不响应

    在我们的程序中,经常会有一些耗时较长的运算,为了保证用户体验,不引起界面不响应,我们一般会采用多线程操作,让耗时操作在后台完成,完成后再进行处理或给出提示,在运行中,也会时时去刷新界面上的进度条等显示 ...

  10. Navisworks Api Quantification

    Quantification  国外有的叫定量  我们国内一些施工方叫工程量. 通过TakeOff API的开发者有机会获得更多的数据和数据可通过图形用户界面. 1 添加Navisworks的Api ...