目录
文件操作
1.打开文件
 
2.操作文件
2.with语句
首页 后端开发 Python教程 python文件操作的方法介绍

python文件操作的方法介绍

Mar 21, 2017 pm 01:06 PM
python

文件操作

1.open()函数

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

1.打开文件

2.操作文件

3.关闭文件

常见的格式示例:

f = open('note.txt','r')
f.read()
f.close()
登录后复制

1.打开文件

文件句柄 = open('文件路径','模式')
登录后复制

常见的模式有:

1.‘r’,只读

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

3.‘a’,追加

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

1.‘r+’

2.‘w+’

3.‘a+’

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

1.‘rb’,‘rb+’

2.‘wb’,‘wb+’

3.‘ab’,‘ab+’

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 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.
        """
        pass

Python 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
        写内容
        pass

Python 3.x
登录后复制

python3操作文件

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

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

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

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

2.with语句

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

如:

with open(&#39;name.txt&#39;, &#39;w&#39;) as f:
    f.write(&#39;Somebody^Fancy1&#39;)
登录后复制

等价于:

try:
    f = open(&#39;name.txt&#39;,&#39;w&#39;)
    f.write(&#39;Somebody^Fancy1&#39;)
finally:
    if f:
        f.close()
登录后复制

以上是python文件操作的方法介绍的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

PHP和Python:代码示例和比较 PHP和Python:代码示例和比较 Apr 15, 2025 am 12:07 AM

PHP和Python各有优劣,选择取决于项目需求和个人偏好。1.PHP适合快速开发和维护大型Web应用。2.Python在数据科学和机器学习领域占据主导地位。

Python vs. JavaScript:社区,图书馆和资源 Python vs. JavaScript:社区,图书馆和资源 Apr 15, 2025 am 12:16 AM

Python和JavaScript在社区、库和资源方面的对比各有优劣。1)Python社区友好,适合初学者,但前端开发资源不如JavaScript丰富。2)Python在数据科学和机器学习库方面强大,JavaScript则在前端开发库和框架上更胜一筹。3)两者的学习资源都丰富,但Python适合从官方文档开始,JavaScript则以MDNWebDocs为佳。选择应基于项目需求和个人兴趣。

CentOS上PyTorch的GPU支持情况如何 CentOS上PyTorch的GPU支持情况如何 Apr 14, 2025 pm 06:48 PM

在CentOS系统上启用PyTorchGPU加速,需要安装CUDA、cuDNN以及PyTorch的GPU版本。以下步骤将引导您完成这一过程:CUDA和cuDNN安装确定CUDA版本兼容性:使用nvidia-smi命令查看您的NVIDIA显卡支持的CUDA版本。例如,您的MX450显卡可能支持CUDA11.1或更高版本。下载并安装CUDAToolkit:访问NVIDIACUDAToolkit官网,根据您显卡支持的最高CUDA版本下载并安装相应的版本。安装cuDNN库:前

docker原理详解 docker原理详解 Apr 14, 2025 pm 11:57 PM

Docker利用Linux内核特性,提供高效、隔离的应用运行环境。其工作原理如下:1. 镜像作为只读模板,包含运行应用所需的一切;2. 联合文件系统(UnionFS)层叠多个文件系统,只存储差异部分,节省空间并加快速度;3. 守护进程管理镜像和容器,客户端用于交互;4. Namespaces和cgroups实现容器隔离和资源限制;5. 多种网络模式支持容器互联。理解这些核心概念,才能更好地利用Docker。

CentOS上PyTorch的分布式训练如何操作 CentOS上PyTorch的分布式训练如何操作 Apr 14, 2025 pm 06:36 PM

在CentOS系统上进行PyTorch分布式训练,需要按照以下步骤操作:PyTorch安装:前提是CentOS系统已安装Python和pip。根据您的CUDA版本,从PyTorch官网获取合适的安装命令。对于仅需CPU的训练,可以使用以下命令:pipinstalltorchtorchvisiontorchaudio如需GPU支持,请确保已安装对应版本的CUDA和cuDNN,并使用相应的PyTorch版本进行安装。分布式环境配置:分布式训练通常需要多台机器或单机多GPU。所

CentOS上PyTorch版本怎么选 CentOS上PyTorch版本怎么选 Apr 14, 2025 pm 06:51 PM

在CentOS系统上安装PyTorch,需要仔细选择合适的版本,并考虑以下几个关键因素:一、系统环境兼容性:操作系统:建议使用CentOS7或更高版本。CUDA与cuDNN:PyTorch版本与CUDA版本密切相关。例如,PyTorch1.9.0需要CUDA11.1,而PyTorch2.0.1则需要CUDA11.3。cuDNN版本也必须与CUDA版本匹配。选择PyTorch版本前,务必确认已安装兼容的CUDA和cuDNN版本。Python版本:PyTorch官方支

vscode怎么在终端运行程序 vscode怎么在终端运行程序 Apr 15, 2025 pm 06:42 PM

在 VS Code 中,可以通过以下步骤在终端运行程序:准备代码和打开集成终端确保代码目录与终端工作目录一致根据编程语言选择运行命令(如 Python 的 python your_file_name.py)检查是否成功运行并解决错误利用调试器提升调试效率

Python:自动化,脚本和任务管理 Python:自动化,脚本和任务管理 Apr 16, 2025 am 12:14 AM

Python在自动化、脚本编写和任务管理中表现出色。1)自动化:通过标准库如os、shutil实现文件备份。2)脚本编写:使用psutil库监控系统资源。3)任务管理:利用schedule库调度任务。Python的易用性和丰富库支持使其在这些领域中成为首选工具。

See all articles