python文件操作的方法介绍

文件操作

1.open()函数

open()函数主要用于文件处理,一般分为下面3个过程:

1.打开文件2.操作文件3.关闭文件

常见的格式示例:

f = open('note.txt','r')f.read()f.close()

登录后复制

1.打开文件

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

登录后复制

常见的模式有:

1.‘r’,只读

2.‘w’,只写(当对打开执行只写操作后,文件原内容将会被清空,注意备份)

立即学习“Python免费学习笔记(深入)”;

3.‘a’,追加

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

1.‘r+’

2.‘w+’

3.‘a+’

“b”表示处理二进制文件

1.‘rb’,‘rb+’

2.‘wb’,‘wb+’

3.‘ab’,‘ab+’

“U”表示在读取时,可以将 自动转换成 (与 r 或 r+ 模式同使用)

1.‘rU’

2.‘r+U’

 

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.        """        passPython 2.x

登录后复制

python2操作文件

class TextIOWrapper(_TextIOBase):    """    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        写内容        passPython 3.x

登录后复制

python3操作文件

但其实常用的操作也就那几个:

f.read(3)   # python2中表示指定读取3个字节,python3中表示指定读取3个字符!f.readline()    # 读取文件内容中的一行f.readlines()   # 自动将文件内容解析为一个,可以用 for line in f.readlines(): 处理f.write('helloPython')f.seek(9)   # 按照字节来执行,用来指定当前文件指针位置,seek(0)表示文件指针移到文件头,seek(0,2)指向文件尾,便于追加内容f.tell()    # 是按照字节来执行的,用来查看当前指针位置

登录后复制

还有一个truncate()函数,用于截断文件内容且仅保留文件内容截断处之前的内容,不容易理解可以看示例:

f = open('test.log','r+',encoding='utf-8')#  encoding='utf-8',有处理汉字的时候这样用f.seek(9)#   原文件内容是‘小苹果helloPython’f.truncate()#执行truncate()后,仅保留原文件截断之前的内容,这里即为‘小苹果’f.close()

登录后复制

2.with语句

上面利用open()函数进行文件处理时,必须在文件打开进行操作后执行f.close()关闭文件,十分的麻烦。而使用with()语句则可以避免这一步繁琐的操作,自动在文件操作后关闭文件。并且,在python中引入with语句的目的是在异常处理中把try,except和finally关键字,以及与资源分配释放相关的代码全部去掉,从而减少代码的编写量,使代码更简洁!

如:

with open('name.txt', 'w') as f:    f.write('Somebody^Fancy1')

登录后复制

等价于:

try:    f = open('name.txt','w')    f.write('Somebody^Fancy1')finally:    if f:        f.close()

登录后复制

以上就是python文件操作的方法介绍的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2275800.html

(0)
上一篇 2025年2月27日 14:47:01
下一篇 2025年2月18日 04:01:04

AD推荐 黄金广告位招租... 更多推荐

相关推荐

  • python2.x 默认编码问题解决方法

    python2.x中处理中文,是一件头疼的事情。网上写这方面的文章,测次不齐,而且都会有点错误,所以在这里打算自己总结一篇文章。 我也会在以后学习中,不断的修改此篇博客。 这里假设读者已有与编码相关的基础知识,本文不再再次介绍,包括什么是u…

    2025年2月27日
    200
  • 使用python-ldap实现登录方法

    这篇文章详解使用python-ldap实现登录方法 ldap_config = {    ‘ldap_path’: ‘ldap://xx.xx.xx.xx:389’,    ‘base_dn’: ‘ou=users,dc=ledo,dc=c…

    编程技术 2025年2月27日
    200
  • python小函数字符类型转换方法

      Python3有两种表示字符序列的类型:bytes和str。前者的实例包含原始的8位值就是的字节,每个字节有8个二进制位;后者的实例包含Unicode字符。把Unicode字符转成二进制数据最常见的编码方式就是UTF-8,必须使用enc…

    编程技术 2025年2月27日
    200
  • python tornado websocket实时日志展示的实例代码

    一、主题:实时展示服务器端动态生成的日志文件 二、流程:   1. 客户端浏览器与服务器建立websocket 链接,服务器挂起保存链接实例,等待新内容触发返回动作   2. 日志服务器脚本循环去发现新内容,发现新行向 tornado等待A…

    编程技术 2025年2月27日
    200
  • 使用python发送和接收邮件实例代码

    关于电子邮件 大学之前,基本不用邮箱,所以基本感觉不到它的存在,也不知道有什么用;然而大学之后,随着认识的人越来越多,知识越来越广泛,邮箱已然成为很重要的通讯工具,大学一些课程作业需要有邮箱发给老师,注册网站需要邮箱,找工作也需要邮箱;那么…

    编程技术 2025年2月27日
    200
  • python文件File输入输出的基本操作方法

    1. python 文件i/o  本章只讲述所有基本的的i/o函数,更多函数请参考python标准文档。 2.打印到屏幕  最简单的输出方法是用print语句,你可以给它传递零个或多个用逗号隔开的表达式。此函数把你传递的表达式转换成一个字符…

    编程技术 2025年2月27日
    200
  • Python学习基础一变量和赋值的详细介绍

    变量:程序在运行的时候会用到很多临时存储数据,这个时候就用到了变量,临时数据的名字。 Python中变量不需要声明,直接可以使用,变量的数据类型由赋值确定。 >>> name=”like”>>> name…

    编程技术 2025年2月27日
    200
  • Linux上使用Python和Flask创建应用的方法

    无论你在linux上娱乐还是工作,这对你而言都是一个使用python来编程的很好的机会。回到大学我希望他们教我的是Python而不是Java,这学起来很有趣且在实际的应用如yum包管理器中很有用。 本篇教程中我会带你使用python和一个称…

    编程技术 2025年2月27日
    200
  • Mac OSX中搭建Python集成开发环境步骤详解

    本篇博客分享如何在mac osx系统中搭建python集成开发环境 首先到Python官网下载python,python官网链接 这里选择下载Python2.7.9版本,下载完成之后安装: 立即学习“Python免费学习笔记(深入)”; 安…

    2025年2月27日 编程技术
    200
  • Python生成XML文件的方法

    这篇文章主要介绍了使用python生成xml的方法,结合具体实例形式详细分析了python生成xml文件的具体流畅与相关注意事项,需要的朋友可以参考下 本文实例讲述了使用Python生成XML的方法。分享给大家供大家参考,具体如下: 1. …

    编程技术 2025年2月27日
    200

发表回复

登录后才能评论