网站首页 > 技术文章 正文
I在 Python 中处理文件是一项常见任务,Python 提供了几个内置函数和模块来帮助您读取、写入和操作文件。以下是在 Python 中处理文件时可以执行的一些基本操作:
- 打开文件:您可以使用该函数在 Python 中打开文件。它有两个参数:文件路径和模式(例如,“r”表示读取,“w”表示写入,“a”表示追加等)。open()
# Opening a file for reading
file = open('example.txt', 'r')
# Opening a file for writing
file = open('example.txt', 'w')
# Opening a file for appending
file = open('example.txt', 'a')
2. 从文件中读取:
可以使用 file 对象提供的各种方法读取文件的内容:
- read():以字符串形式读取整个文件内容。
- readline():一次读取一行。
- readlines():读取所有行并将它们作为列表返回。
# Reading the entire file
content = file.read()
# Reading one line at a time
line = file.readline()
# Reading all lines into a list
lines = file.readlines()
3. 写入文件:
若要将数据写入文件,请使用该方法。write()
# Writing data to a file
file.write("Hello, world!")
4. 附加到文件:
若要将数据追加到现有文件的末尾,请使用“a”模式或具有追加模式的方法。write()
# Appending data to a file
file = open('example.txt', 'a')
file.write("Appending text")
5. 关闭文件:
使用完文件后关闭文件以释放系统资源非常重要。
file.close()
或者,可以使用语句,该语句在您完成文件后自动关闭文件:with
with open('example.txt', 'r') as file:
content = file.read()
# File is automatically closed when the block exits.
6. 遍历行:
可以使用循环遍历文件的行。for
with open('example.txt', 'r') as file:
for line in file:
print(line)
7.文件模式:
- 'r':读取(默认)。
- 'w':写入(创建新文件或截断现有文件)。
- 'a':追加(创建新文件或追加到现有文件)。
- 'b':二进制模式(例如,用于读取二进制文件)。'rb'
- 't':文本模式(默认)。
8. 文件处理错误:
在处理文件时,尤其是在打开和读取/写入文件时,请始终处理异常。
try:
with open('example.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("File not found.")
except IOError:
print("An error occurred while reading the file.")
猜你喜欢
- 2025-05-02 python执行.sql语法和文件(python oracle sql语句跟参数)
- 2025-05-02 python unittest 基本用法(python中testcase)
- 2025-05-02 免费定时运行Python程序并存储输出文档的服务推荐
- 2025-05-02 20 天学 Python 文件操作:Day 1 从 open() 开始
- 2025-05-02 一文掌握Python找到文件操作(python找到文件夹下指定文件)
- 2025-05-02 python 文件操作(python 文件操作模块)
- 2025-05-02 pdb,让python文件在linux中跑起来
- 2025-05-02 IDEA中配置Python环境并运行(idea 运行python)
- 2025-05-02 14《Python 办公自动化教程》os 模块操作文件与文件夹
- 2025-05-02 Python自动化办公自学笔记(八)文件操作
- 258℃Python短文,Python中的嵌套条件语句(六)
- 258℃python笔记:for循环嵌套。end=""的作用,图形打印
- 257℃PythonNet:实现Python与.Net代码相互调用!
- 252℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 252℃Python实现字符串小写转大写并写入文件
- 108℃原来2025是完美的平方年,一起探索六种平方的算吧
- 91℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 83℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)