python文件读写操作的三大基本步骤

简介: python文件读写操作的三大基本步骤

基本步骤

1. 打开文件:open(filepath, mode, encoding)

2. 读写文件:read() / write()

3. 关闭文件:close()

python读取文件操作实例

f = open('filename.txt', 'r', encoding='utf-8')

f.read()

f.close()

常用函数

open()函数

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

file是要打开的文件,mode='r'是打开文件的模式,encoding是编码格式

文件的打开模式有以下字符表示:

    'r'       open for reading (default)
    'w'       open for writing, truncating the file first
    'x'       create a new file and open it for writing
    'a'       open for writing, appending to the end of the file if it exists
    'b'       binary mode
    't'       text mode (default)
    '+'       open a disk file for updating (reading and writing)

打开模式还能连用:

The default mode is 'rt' (open for reading text). For binary random  access, the mode 'w+b' opens and truncates the file to 0 bytes, while 'r+b' opens the file without truncation. The 'x' mode implies 'w' and raises an `FileExistsError` if the file already exists.

close()函数

close() method of _io.TextIOWrapper instance
    Flush and close the IO object.

    This method has no effect if the file is already closed

打开文件,必须有对应的关闭,否则该未关闭的文件不能被其它的应用操作。

read()函数

read(size=-1, /) method of _io.TextIOWrapper instance
    Read at most size characters from stream.

    Read from underlying buffer until we have size characters or we hit EOF.
    If size is negative or omitted, read until EOF.

read()可选参数size可以用于读取“size”大小的数据,返回的是字符串或字节对象,若是size的值没有填写,或者是个负值,那么read()函数将读取文件的所有内容,这也是用python开发pc软件中“复制黏贴”的功能比较常用的函数。

readlines()函数

Help on built-in function readlines:

readlines(hint=-1, /) method of _io.TextIOWrapper instance
    Return a list of lines from the stream.

    hint can be specified to control the number of lines read: no more
    lines will be read if the total size (in bytes/characters) of all
    lines so far exceeds hint.

readlines()函数是将文件当中的所有行,一行一行地读取,并逐一写入一个列表list内,最终返回这个列表。

readline()函数

Help on built-in function readline:

readline(size=-1, /) method of _io.TextIOWrapper instance
    Read until newline or EOF.

    Return an empty string if EOF is hit immediately.
    If size is specified, at most size characters will be read.

readline()函数就是读取一行数据,用法除了size参数之外,就跟read()差不多,也是open()打开文件,readline()读取数据,close()关闭文件

write()函数

write(text, /) method of _io.TextIOWrapper instance
    Write string s to stream.

    Return the number of characters written
    (which is always equal to the length of the string).

writelines()函数

writelines(lines, /) method of _io.TextIOWrapper instance

   Write a list of lines to stream.

   Line separators are not added, so it is usual for each of the

   lines provided to have a line separator at the end.

with语句

通过with语句,不管读取还是写入文件操作都不用写对应的close()函数,语句块结束系统会自动关闭文件。

with open('filename.txt', 'r', encoding='urf-8') as f:
    f.read()

读写操作的应用:

拷贝文件

# 打开源文件以读取内容  
with open('source.txt', 'r') as source_file:  
    source_content = source_file.read()  
  
# 打开目标文件以写入内容  
with open('destination.txt', 'w') as destination_file:  
    destination_file.write(source_content)

with 语句的嵌套

以上两个with语句块还能嵌套写在一起

# 打开源文件以读取内容,并同时打开目标文件以写入内容  
with open('source.txt', 'r') as source_file:  
    with open('destination.txt', 'w') as destination_file:  
        # 读取源文件的内容  
        source_content = source_file.read()  
        # 将读取的内容写入到目标文件中  
        destination_file.write(source_content)

可以写在同一行

# 打开源文件以读取内容,并同时打开目标文件以写入内容  
with open('source.txt', 'r') as source_file, open('destination.txt', 'w') as destination_file:  
    # 读取源文件的内容  
    source_content = source_file.read()  
    # 将读取的内容写入到目标文件中  
    destination_file.write(source_content)

逐行拷贝

如果源文件很大,使用read()方法一次性读取所有内容可能会消耗较多的内存。对于大文件,更推荐的做法是使用文件对象的迭代器逐行读取和写入,这样可以减少内存的使用。

with open('source.txt', 'r') as source_file, open('destination.txt', 'w') as destination_file:  
    # 逐行读取源文件并写入目标文件  
    for line in source_file:  
        destination_file.write(line)

目录
相关文章
|
3月前
|
数据可视化 Linux iOS开发
Python脚本转EXE文件实战指南:从原理到操作全解析
本教程详解如何将Python脚本打包为EXE文件,涵盖PyInstaller、auto-py-to-exe和cx_Freeze三种工具,包含实战案例与常见问题解决方案,助你轻松发布独立运行的Python程序。
1016 2
|
2月前
|
监控 机器人 编译器
如何将python代码打包成exe文件---PyInstaller打包之神
PyInstaller可将Python程序打包为独立可执行文件,无需用户安装Python环境。它自动分析代码依赖,整合解释器、库及资源,支持一键生成exe,方便分发。使用pip安装后,通过简单命令即可完成打包,适合各类项目部署。
|
4月前
|
缓存 数据可视化 Linux
Python文件/目录比较实战:排除特定类型的实用技巧
本文通过四个实战案例,详解如何使用Python比较目录差异并灵活排除特定文件,涵盖基础比较、大文件处理、跨平台适配与可视化报告生成,助力开发者高效完成目录同步与数据校验任务。
160 0
|
5月前
|
编译器 Python
如何利用Python批量重命名PDF文件
本文介绍了如何使用Python提取PDF内容并用于文件重命名。通过安装Python环境、PyCharm编译器及Jupyter Notebook,结合tabula库实现PDF数据读取与处理,并提供代码示例与参考文献。
|
5月前
|
编译器 Python
如何利用Python批量重命名文件
本文介绍了如何使用Python和PyCharm对文件进行批量重命名,包括文件名前后互换、按特定字符调整顺序等实用技巧,并提供了完整代码示例。同时推荐了第三方工具Bulk Rename Utility,便于无需编程实现高效重命名。适用于需要处理大量文件命名的场景,提升工作效率。
|
5月前
|
安全 Linux 网络安全
Python极速搭建局域网文件共享服务器:一行命令实现HTTPS安全传输
本文介绍如何利用Python的http.server模块,通过一行命令快速搭建支持HTTPS的安全文件下载服务器,无需第三方工具,3分钟部署,保障局域网文件共享的隐私与安全。
1014 0
|
5月前
|
数据管理 开发工具 索引
在Python中借助Everything工具实现高效文件搜索的方法
使用上述方法,你就能在Python中利用Everything的强大搜索能力实现快速的文件搜索,这对于需要在大量文件中进行快速查找的场景尤其有用。此外,利用Python脚本可以灵活地将这一功能集成到更复杂的应用程序中,增强了自动化处理和数据管理的能力。
352 0
|
6月前
|
编解码 Prometheus Java
当Python同时操作1000个文件时,为什么你的CPU只用了10%?
本文介绍如何构建一个高效的文件处理系统,解决单线程效率低、多线程易崩溃的矛盾。通过异步队列与多线程池结合,实现任务调度优化,提升I/O密集型操作的性能。
141 4
|
5月前
|
数据采集 监控 算法
Python文件与目录比较全攻略:从基础操作到性能优化
文件比较的核心在于数据指纹校验,通过逐字节比对生成唯一标识,确保内容一致性。从标准库的os与filecmp到高性能第三方库如pydiffx,再到分布式与量子加密技术的未来趋势,文件比较广泛应用于数据备份、代码审查与系统监控等领域,是保障数据完整性的关键技术手段。
115 0
|
6月前
|
数据采集 存储 API
Python爬虫结合API接口批量获取PDF文件
Python爬虫结合API接口批量获取PDF文件

推荐镜像

更多