本篇主要内容:open文件处理函数的使用

open函数,该函数用于文件处理

操作文件时,一般需要经历如下步骤:

  • 打开文件
  • 操作文件

一、打开文件

文件句柄 = open('文件路径', '模式')

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

  • r ,只读模式【默认】
  • w,只写模式【不可读;不存在则创建;存在则清空内容;】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+, 读写【可读,可写】
  • w+,写读【可读,可写】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】

"b"表示以字节的方式操作

  • rb  或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型

二、操作

python2.x

class file(object)
def close(self): # real signature unknown; restored from __doc__
关闭文件
"""
close() -> None or (perhaps) an integer. Close the file. Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by popen())
may return an exit status upon closing.
"""
...
...
...

python3.x

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.
"""
def close(self, *args, **kwargs): # real signature unknown
关闭文件
pass def fileno(self, *args, **kwargs): # real signature unknown
文件描述符
pass def flush(self, *args, **kwargs): # real signature unknown
刷新文件内部缓冲区
pass def isatty(self, *args, **kwargs): # real signature unknown
判断文件是否是同意tty设备
pass def read(self, *args, **kwargs): # real signature unknown
读取指定字节数据
pass def readable(self, *args, **kwargs): # real signature unknown
是否可读
pass def readline(self, *args, **kwargs): # real signature unknown
仅读取一行数据
pass def seek(self, *args, **kwargs): # real signature unknown
指定文件中指针位置
pass def seekable(self, *args, **kwargs): # real signature unknown
指针是否可操作
pass def tell(self, *args, **kwargs): # real signature unknown
获取指针位置
pass def truncate(self, *args, **kwargs): # real signature unknown
截断数据,仅保留指定之前数据
pass def writable(self, *args, **kwargs): # real signature unknown
是否可写
pass def write(self, *args, **kwargs): # real signature unknown
写内容
pass def __getstate__(self, *args, **kwargs): # real signature unknown
pass def __init__(self, *args, **kwargs): # real signature unknown
pass @staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass def __next__(self, *args, **kwargs): # real signature unknown
""" Implement next(self). """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 3.x

三、管理上下文

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

with open('log','r') as f:

    ...

  

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 及以后,with又支持同时对多个文件的上下文进行管理,即:

with open('log1') as obj1, open('log2') as obj2:
pass

  

[Python笔记]第六篇:文件处理的更多相关文章

  1. python学习笔记(六)文件夹遍历,异常处理

    python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...

  2. python第六篇文件处理类型

    阅读目录 一 文件操作 二 打开文件的模式 三 操作文件的方法 四 文件内光标移动 五 文件的修改   文件处理                                             ...

  3. Python学习笔记 -- 第六章 文件操作

    I/O编程 在磁盘上读写文件的功能都是由操作系统提供的,现代操作系统不允许普通的程序直接操作磁盘,所以,读写文件就是请求操作系统打开一个文件对象(通常称为文件描述符),然后,通过操作系统提供的接口从这 ...

  4. Python笔记_第一篇_面向过程_第一部分_7.文件的操作(.txt)

    在平时,我们不光要对程序内的代码进行输入和输出的操作,还要对程序外的文件进行和语言之间的交换.操作和运算.在基础部分,先讲解对于外部的.txt文件的操作. 第一部分 基本内容讲解 1.   什么是文件 ...

  5. [Python笔记]第四篇:内置函数

    本篇主要内容:内置函数 函数 参考:https://docs.python.org/3.5/library/functions.html 内置函数列表 一.数学运算类 abs(x)求绝对值 >& ...

  6. 图解Python 【第六篇】:面向对象-类-进阶篇

    由于类的内容比较多,分为类-初级基础篇和类-进阶篇 本节内容一览图: 一.类成员修饰符 每一个类的成员都有两种形式: 公有成员,在任何地方都能访问 私有成员,只能在类的内部才能访问 1.1.私有成员和 ...

  7. [Python笔记]第八篇:模块

    本篇主要内容:python常用模块用法介绍 什么是模块 模块,用一大段代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性 ...

  8. 我们一起学习WCF 第六篇文件传输

    原文  http://www.cnblogs.com/LipeiNet/p/4653830.html   前言:文件的输出我们并不陌生,但是今天我写的是用wcf模式进行文件传输,我觉得一大好处就是能进 ...

  9. python基础-第六篇-6.2模块

    python之强大,就是因为它其提供的模块全面,模块的知识点不仅多,而且零散---一个字!错综复杂 没办法,二八原则抓重点咯!只要抓住那些以后常用开发的方法就可以了,哪些是常用的?往下看--找答案~ ...

随机推荐

  1. [Locked] Smallest Rectangle Enclosing Black Pixels

    An image is represented by a binary matrix with 0 as a white pixel and 1 as a black pixel. The black ...

  2. MYSQL: Cannot delete or update a parent row: a foreign key constraint fails

    这可能是MySQL在InnoDB中设置了foreign key关联,造成无法更新或删除数据.可以通过设置FOREIGN_KEY_CHECKS变量来避免这种情况. SET FOREIGN_KEY_CHE ...

  3. 使用JAVA与SmartFoxServer来实现游戏服务器概述

    SmartFoxServer 是专门为Adobe Flash设计的跨平台socket服务器,让开发者高效地开发多人应用及游戏. 该服务器主要用来创建多玩家游戏.并提供强大的制作工具,各种回合制游戏和实 ...

  4. php字符编码转utf-8格式

    <? function is_utf8($other) { if (preg_match("/^([".chr(228)."-".chr(233).&qu ...

  5. TeleMCU视频会议之Android版本号WebRTC client支持

    本文原创自 http://blog.csdn.net/voipmaker  转载注明出处. 最新版本号TeleMCU 添加了Android手机端WebRTC视频会议能力,Android手机安装Chro ...

  6. HDU 5120 Intersection(几何模板题)

    题意:给定两个圆环,求两个圆环相交的面积. 思路:由于圆心和半径不一样,分了好多种情况,后来发现只要把两个圆相交的函数写好之后就不需要那么复杂了.两个圆相交的面积的模板如下: double area_ ...

  7. Python之路,Day15 - Django适当进阶篇

    Python之路,Day15 - Django适当进阶篇   本节内容 学员管理系统练习 Django ORM操作进阶 用户认证 Django练习小项目:学员管理系统设计开发 带着项目需求学习是最有趣 ...

  8. 对话框 自定义 IOS风格 包青天

    activity     private void showDialog1() {         message = "您输入的邮箱后缀不是公司邮箱地址\n将导致您的借款审核不通过,请重新 ...

  9. C#中接口和抽象类

    1抽象类 (1) 抽象方法只作声明,而不包含实现,可以看成是没有实现体的虚方法 (2) 抽象类不能被实例化 (3) 抽象类可以但不是必须有抽象属性和抽象方法,但是一旦有了抽象方法,就一定要把这个类声明 ...

  10. HTML-点击收藏功能模块

    先上效果图: 功能简单: 附上源码以及注解 <div class="info-attribute" id="collect"> <input ...