本篇主要内容: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. java工作流bpm开发ERP实例

    今天看了一个java工作流bpm开发ERP的例子,文章介绍:http://tech.it168.com/a2009/0507/275/000000275294_14.shtml 增加数据块 一路照做就 ...

  2. [Audio processing] wav音频文件合并

    合并多个文件,需要包含1.文件读取和写入功能,2.数组合并 package com.audioprocessingbox.myfunc; import java.io.File; import jav ...

  3. 嵌套fragment时必须要重写 onDetach()

    /**     * 嵌套fragment时必须要重写 onDetach()如下     */ @Override public void onDetach() { super.onDetach(); ...

  4. hibernate生成查询语句但查不到数据

    hibernate能够生成查询语句 说明它已经进行了查询操作 返回结果数据记录为0  很可能出现的情况 是  :该查询未未访问到指定数据库表. 当使用的数据库为oracle数据库时,你会在bean配置 ...

  5. 在反射中Member{get{..}set{..}}与Member{get;set;}的区别?

    最近的在写代码的时候,需要用到反射来获取类中的所有公开属性值,于是写下如下代码: StringBuilder sb = new StringBuilder(); foreach (var f in t ...

  6. WebChat 清爽来袭 -- JavaChat系统Ⅳ

    题记:          WebChat 依然搭配的是 JavaChat 服务器,在不修改原来服务器代码的情况下进行使用终端的扩展.         此次项目的难点在于,Action/Servlet ...

  7. 黑马程序猿_try-catch-finally

    ------- android培训.java培训.期待与您交流! ---------- try-catch-finally中怎样定义语句呢? 1.try块中主要定义可能出现的异常处理语句 2.catc ...

  8. CSDN markdown 编辑器 第四篇 LaTex语法

    Latex是为了写数学公式的. 嗯-但实际这样的语言的作用是为了排版的.数学公式仅仅是他的附加属性. 可是markdown引入这个全然是为了写公式.其它的Latex语法不支持. CSDN markdo ...

  9. Android Rom修改

    最近项目里要实现修改开机动画 屏蔽系统桌面等一些涉及到修改底层的功能 一开始研究了一番 心想着看来这是要定制系统 做rom开发了 所以就牛逼哄哄的跑去下源码 研究rom开发 后来发现这将是一个庞大的工 ...

  10. 从页面底部向上弹出dialog,消失时逐渐向下(转)

    我想实现一个效果,从底部向上逐渐弹出.如下图所示: 1.点击 显示 按钮时,一个dialog对话框从底部慢慢向上弹出. 2.关闭dialog时, dialog缓慢的移动向底部消失.很平滑的效果.   ...