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)

目录
相关文章
|
1月前
|
机器学习/深度学习 存储 算法
解锁文件共享软件背后基于 Python 的二叉搜索树算法密码
文件共享软件在数字化时代扮演着连接全球用户、促进知识与数据交流的重要角色。二叉搜索树作为一种高效的数据结构,通过有序存储和快速检索文件,极大提升了文件共享平台的性能。它依据文件名或时间戳等关键属性排序,支持高效插入、删除和查找操作,显著优化用户体验。本文还展示了用Python实现的简单二叉搜索树代码,帮助理解其工作原理,并展望了该算法在分布式计算和机器学习领域的未来应用前景。
|
2月前
|
监控 网络安全 开发者
Python中的Paramiko与FTP文件夹及文件检测技巧
通过使用 Paramiko 和 FTP 库,开发者可以方便地检测远程服务器上的文件和文件夹是否存在。Paramiko 提供了通过 SSH 协议进行远程文件管理的能力,而 `ftplib` 则提供了通过 FTP 协议进行文件传输和管理的功能。通过理解和应用这些工具,您可以更加高效地管理和监控远程服务器上的文件系统。
61 20
|
2月前
|
存储 数据采集 数据处理
如何在Python中高效地读写大型文件?
大家好,我是V哥。上一篇介绍了Python文件读写操作,今天聊聊如何高效处理大型文件。主要方法包括:逐行读取、分块读取、内存映射(mmap)、pandas分块处理CSV、numpy处理二进制文件、itertools迭代处理及linecache逐行读取。这些方法能有效节省内存,提升效率。关注威哥爱编程,学习更多Python技巧。
103 8
|
2月前
|
存储 JSON 对象存储
如何使用 Python 进行文件读写操作?
大家好,我是V哥。本文介绍Python中文件读写操作的方法,包括文件读取、写入、追加、二进制模式、JSON、CSV和Pandas模块的使用,以及对象序列化与反序列化。通过这些方法,你可以根据不同的文件类型和需求,灵活选择合适的方式进行操作。希望对正在学习Python的小伙伴们有所帮助。欢迎关注威哥爱编程,全栈路上我们并肩前行。
|
4月前
|
测试技术 Python
手动解决Python模块和包依赖冲突的具体步骤是什么?
需要注意的是,手动解决依赖冲突可能需要一定的时间和经验,并且需要谨慎操作,避免引入新的问题。在实际操作中,还可以结合使用其他方法,如虚拟环境等,来更好地管理和解决依赖冲突😉。
|
2月前
|
存储 算法 Serverless
剖析文件共享工具背后的Python哈希表算法奥秘
在数字化时代,文件共享工具不可或缺。哈希表算法通过将文件名或哈希值映射到存储位置,实现快速检索与高效管理。Python中的哈希表可用于创建简易文件索引,支持快速插入和查找文件路径。哈希表不仅提升了文件定位速度,还优化了存储管理和多节点数据一致性,确保文件共享工具高效运行,满足多用户并发需求,推动文件共享领域向更高效、便捷的方向发展。
|
2月前
|
安全 数据挖掘 编译器
【01】优雅草央央逆向技术篇之逆向接口协议篇-如何用python逆向接口协议?python逆向接口协议的原理和步骤-优雅草央千澈
【01】优雅草央央逆向技术篇之逆向接口协议篇-如何用python逆向接口协议?python逆向接口协议的原理和步骤-优雅草央千澈
88 6
|
3月前
|
计算机视觉 Python
如何使用Python将TS文件转换为MP4
本文介绍了如何使用Python和FFmpeg将TS文件转换为MP4文件。首先需要安装Python和FFmpeg,然后通过`subprocess`模块调用FFmpeg命令,实现文件格式的转换。代码示例展示了具体的操作步骤,包括检查文件存在性、构建FFmpeg命令和执行转换过程。
88 7
|
4月前
|
中间件 Docker Python
【Azure Function】FTP上传了Python Function文件后,无法在门户页面加载函数的问题
通过FTP上传Python Function至Azure云后,出现函数列表无法加载的问题。经排查,发现是由于`requirements.txt`中的依赖包未被正确安装。解决方法为:在本地安装依赖包到`.python_packages/lib/site-packages`目录,再将该目录内容上传至云上的`wwwroot`目录,并重启应用。最终成功加载函数列表。
|
6天前
|
机器学习/深度学习 存储 设计模式
Python 高级编程与实战:深入理解性能优化与调试技巧
本文深入探讨了Python的性能优化与调试技巧,涵盖profiling、caching、Cython等优化工具,以及pdb、logging、assert等调试方法。通过实战项目,如优化斐波那契数列计算和调试Web应用,帮助读者掌握这些技术,提升编程效率。附有进一步学习资源,助力读者深入学习。

热门文章

最新文章

推荐镜像

更多