打开文件、文件操作、管理上下文

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

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

打开文件的模式有:

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

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

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

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

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

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

2.文件操作

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.
        """

    def fileno(self): # real signature unknown; restored from __doc__
        文件描述符
         """
        fileno() -> integer "file descriptor".

        This is needed for lower-level file interfaces, such os.read().
        """
        return 0    

    def flush(self): # real signature unknown; restored from __doc__
        刷新文件内部缓冲区
        """ flush() -> None.  Flush the internal I/O buffer. """
        pass

    def isatty(self): # real signature unknown; restored from __doc__
        判断文件是否是同意tty设备
        """ isatty() -> true or false.  True if the file is connected to a tty device. """
        return False

    def next(self): # real signature unknown; restored from __doc__
        获取下一行数据,不存在,则报错
        """ x.next() -> the next value, or raise StopIteration """
        pass

    def read(self, size=None): # real signature unknown; restored from __doc__
        读取指定字节数据
        """
        read([size]) -> read at most size bytes, returned as a string.

        If the size argument is negative or omitted, read until EOF is reached.
        Notice that when in non-blocking mode, less data than what was requested
        may be returned, even if no size parameter was given.
        """
        pass

    def readinto(self): # real signature unknown; restored from __doc__
        读取到缓冲区,不要用,将被遗弃
        """ readinto() -> Undocumented.  Don‘t use this; it may go away. """
        pass

    def readline(self, size=None): # real signature unknown; restored from __doc__
        仅读取一行数据
        """
        readline([size]) -> next line from the file, as a string.

        Retain newline.  A non-negative size argument limits the maximum
        number of bytes to return (an incomplete line may be returned then).
        Return an empty string at EOF.
        """
        pass

    def readlines(self, size=None): # real signature unknown; restored from __doc__
        读取所有数据,并根据换行保存值列表
        """
        readlines([size]) -> list of strings, each a line from the file.

        Call readline() repeatedly and return a list of the lines so read.
        The optional size argument, if given, is an approximate bound on the
        total number of bytes in the lines returned.
        """
        return []

    def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
        指定文件中指针位置
        """
        seek(offset[, whence]) -> None.  Move to new file position.

        Argument offset is a byte count.  Optional argument whence defaults to
(offset from start of file, offset should be >= 0); other values are 1
        (move relative to current position, positive or negative), and 2 (move
        relative to end of file, usually negative, although many platforms allow
        seeking beyond the end of a file).  If the file is opened in text mode,
        only offsets returned by tell() are legal.  Use of other offsets causes
        undefined behavior.
        Note that not all file objects are seekable.
        """
        pass

    def tell(self): # real signature unknown; restored from __doc__
        获取当前指针位置
        """ tell() -> current file position, an integer (may be a long integer). """
        pass

    def truncate(self, size=None): # real signature unknown; restored from __doc__
        截断数据,仅保留指定之前数据
        """
        truncate([size]) -> None.  Truncate the file to at most size bytes.

        Size defaults to the current file position, as returned by tell().
        """
        pass

    def write(self, p_str): # real signature unknown; restored from __doc__
        写内容
        """
        write(str) -> None.  Write string str to file.

        Note that due to buffering, flush() or close() may be needed before
        the file on disk reflects the data written.
        """
        pass

    def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
        将一个字符串列表写入文件
        """
        writelines(sequence_of_strings) -> None.  Write the strings to the file.

        Note that newlines are not added.  The sequence can be any iterable object
        producing strings. This is equivalent to calling write() for each string.
        """
        pass

    def xreadlines(self): # real signature unknown; restored from __doc__
        可用于逐行读取文件,非全部
        """
        xreadlines() -> returns self.

        For backward compatibility. File objects now include the performance
        optimizations previously implemented in the xreadlines module.
        """
        pass

2.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

3.管理上下文

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

1 with open(‘log‘,‘r‘) as f:
2         
3     ...

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

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

1 with open(‘log1‘) as obj1, open(‘log2‘) as obj2:
2     pass
时间: 2024-12-21 04:43:52

打开文件、文件操作、管理上下文的相关文章

文件的三种打开方式以及with管理上下文

一.文件的三种打开方式 1.1 只读 f = open(r'D:\pycharm\yjy\上海python学习\456.txt','r',encoding='utf8') data = f.read() #读取文件 print(data) f.close() 读的其他语法 逐行读.是否可读 print(1,f.readline()) # 逐行读 print(f.readable()) # 是否可读 # True ps:如果我们需要读文件里面的每一行代码,我们可以用for循环,举个栗子 for i

无法打开物理文件 操作系统错误 5:拒绝访问 SQL Sever

今天分离附加数据库,分离出去然后再附加,没有问题.但是一把.mdf文件拷到其它文件夹下就出错,错误如下:    无法打开物理文件 "E:\db\homework.mdf".操作系统错误 5:"5(拒绝访问.)". (Microsoft SQL Server,错误: 5120) 问了下朋友,朋友说找到.mdf文件改文件的安全权限. 搞了半天才明白,原来是找到.mdf文件,右键->属性->安全->选择当前用户->编辑->完全控制. 如果还出

无法打开物理文件 XXX.mdf",操作系统错误 5:"5(拒绝访问。)"的解决办法

http://blog.csdn.net/blackfield/article/details/6550499 用T-SQL命令附加数据库时,出现如下异常信息: 无法打开物理文件 XXX.mdf".操作系统错误 5:"5(拒绝访问.)". (Microsoft SQL Server,错误: 5120) 解决方案: 找到xxx.MDF与xxx_log.LDF文件,右键-属性-安全-在组或用户名处添加Authenticated Users-更改该组权限为完全权限,再次附加成功.

【Linux命令详解】2、文件和目录操作管理

2.文件和目录操作管理 本节主要学习在Linux下如何使用命令对文件和目录进行操作,这些命令pwd.cd.ls等. 2.1 pwd:显示工作目录路径 使用pwd命令可以显示当前用户所处的工作目录的绝对路径. 2.1.1命令语法: pwd[选项] 2.1.2参数选项: 选项 选项含义 -L 目录链接时,输出链接路径 -P 输出物理路径 2.1.3实例: 例1:显示用户当前工作目录路径. [[email protected] ~]# pwd /root //用户当前的工作路径是root 例2:显示用

maven-jetty-plugin保存文件报错:请求的操作无法在使用用户映射区域打开的文件上执行

使用jetty-maven-plugin 在eclipse中进行运行调试,碰到无法编辑保存webapp下的文件 提示:请求的操作无法在使用用户映射区域打开的文件上执行 解决方法: 从 jetty 7 开始,jar存放在maven仓库中的路径为org/eclise/jetty/jetty-webapp 打开对应的版本的jar包修改jar中的org/mortbay/jetty/webapp/webdefault.xml文件 Java代码 <init-param> <param-name>

无法打开物理文件mdf,操作系统错误 5:&amp;quot;5(拒绝訪问。)&amp;quot;

无法打开物理文件mdf,操作系统错误 5:"5(拒绝訪问.)" 环境: SQL Server 2008 R2 问题: 附加数据库时报错"无法打开物理文件mdf.操作系统错误5:5(拒绝訪问). 解决方式: 找到要附加的mdf文件->右键->属性->安全->选择当前用户->编辑,勾选全然控制权限,确定. 对log文件同样操作.

C#中的Excel操作【1】——设置Excel单元格的内容,打开Excel文件的一种方式

前言 作为项目管理大队中的一员,在公司里面接触最多的就是Excel文件了,所以一开始就想从Excel入手,学习简单的二次开发,开始自己的编程之路! 程序界面 功能说明 打开文件按钮,可以由使用者指定要操作的Excel文件,并在后面的textBox中显示出文件路径. 设置单元格按钮,可以根据程序设置Excel文件的内容. 退出程序按钮,关闭窗体. 程序源代码 1 using System; 2 using System.Collections.Generic; 3 using System.Com

无法打开物理文件 &quot;D:\understructuredata _DAT.MDF&quot;。操作系统错误 5:&quot;5(拒绝访问。)&quot;

错误信息: 标题: Microsoft SQL Server Management Studio ------------------------------ 附加数据库 对于 服务器"HC-PC"失败. (Microsoft.SqlServer.Smo) 有关帮助信息,请单击: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.50.1600.1+((KJ_RTM).100402-1

win7+SQL2008无法打开物理文件 操作系统错误 5:拒绝访问 SQL Sever

今天在win7+SQL2008的环境下操作分离附加数据库,分离出去然后再附加,没有问题.但是一把.mdf文件拷到其它文件夹下就出错,错误如下:无法打开物理文件 "E:\db\MyDB.mdf".操作系统错误 5:"5(拒绝访问.)". (Microsoft SQL Server,错误: 5120)问了下朋友,朋友说找到.mdf文件改文件的安全权限.搞了半天才明白,原来是找到.mdf文件,右键->属性->安全->选择当前用户->编辑->完