博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Python笔记]第六篇:文件处理
阅读量:5217 次
发布时间:2019-06-14

本文共 5331 字,大约阅读时间需要 17 分钟。

本篇主要内容: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.        """.........
View Code

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)  # default3.x
View Code

 

三、管理上下文

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

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

  

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

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

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

  

 

转载于:https://www.cnblogs.com/yaohan/p/5493123.html

你可能感兴趣的文章
BootScrap
查看>>
[大牛翻译系列]Hadoop(16)MapReduce 性能调优:优化数据序列化
查看>>
WEB_点击一百万次
查看>>
CodeForces - 878A Short Program(位运算)
查看>>
路冉的JavaScript学习笔记-2015年1月23日
查看>>
Mysql出现(10061)错误提示的暴力解决办法
查看>>
2018-2019-2 网络对抗技术 20165202 Exp3 免杀原理与实践
查看>>
NPM慢怎么办 - nrm切换资源镜像
查看>>
CoreData 从入门到精通(四)并发操作
查看>>
Swift - UIView的常用属性和常用方法总结
查看>>
Swift - 异步加载各网站的favicon图标,并在单元格中显示
查看>>
Java编程思想总结笔记Chapter 5
查看>>
[LeetCode]662. Maximum Width of Binary Tree判断树的宽度
查看>>
WinForm聊天室
查看>>
【Python学习笔记】1.基础知识
查看>>
梦断代码阅读笔记02
查看>>
selenium学习中遇到的问题
查看>>
大数据学习之一——了解简单概念
查看>>
Linux升级内核教程(CentOS7)
查看>>
Lintcode: Partition Array
查看>>