目录
"""
1.写入文件
"""
# (1) 打开文件
fp = open("ceshi.txt", mode="a", encoding="utf-8")
# (2) 写入内容
fp.write("大家好!我是python")
# (3)关闭文件
fp.close()
"""
2.文件读取操作
"""
# (1) 打开文件
fp = open("ceshi.txt", mode="r", encoding="utf-8")
# (2) 读取内容
res = fp.read()
# (3)关闭文件
fp.close()
print(res)
代码说明
这段 Python 代码主要完成了两个基本的文件操作:文件写入和文件读取。下面我们逐步详细解释代码的各个部分。
1. 文件写入操作
# (1) 打开文件
fp = open("ceshi.txt", mode="a", encoding="utf-8")
# (2) 写入内容
fp.write("大家好!我是python")
# (3)关闭文件
fp.close()
-
打开文件:
open("ceshi.txt", mode="a", encoding="utf-8")
:open
是 Python 内置函数,用于打开一个文件。这里的参数含义如下:"ceshi.txt"
:指定要打开的文件的名称。如果文件不存在,在写入模式下会自动创建该文件。mode="a"
:指定文件的打开模式。"a"
表示追加模式,即如果文件已经存在,新写入的内容会被添加到文件的末尾;如果文件不存在,则会创建一个新文件。encoding="utf-8"
:指定文件的编码方式。"utf-8"
是一种通用的字符编码,能够处理各种语言的字符。
fp
是一个文件对象,它代表了打开的文件,后续的写入操作将通过这个对象来进行。
-
写入内容:
fp.write("大家好!我是python")
:调用文件对象fp
的write
方法,将字符串"大家好!我是python"
写入到文件中。
-
关闭文件:
fp.close()
:调用文件对象的close
方法,关闭文件。关闭文件是一个良好的编程习惯,它可以释放系统资源,确保文件操作的完整性。
2. 文件读取操作
# (1) 打开文件
fp = open("ceshi.txt", mode="r", encoding="utf-8")
# (2) 读取内容
res = fp.read()
# (3)关闭文件
fp.close()
print(res)
-
打开文件:
open("ceshi.txt", mode="r", encoding="utf-8")
:同样使用open
函数打开文件。这里的参数含义如下:"ceshi.txt"
:指定要打开的文件的名称。mode="r"
:指定文件的打开模式。"r"
表示只读模式,即只能从文件中读取内容,不能对文件进行写入操作。encoding="utf-8"
:指定文件的编码方式,确保正确读取文件中的字符。
fp
是一个文件对象,用于后续的读取操作。
-
读取内容:
res = fp.read()
:调用文件对象fp
的read
方法,将文件中的所有内容读取到一个字符串中,并将该字符串赋值给变量res
。
-
关闭文件:
fp.close()
:关闭文件,释放系统资源。
-
输出结果:
print(res)
:将读取到的文件内容打印输出。
同类操作
写入操作的其他模式
- 写入模式
"w"
:
fp = open("ceshi.txt", mode="w", encoding="utf-8")
fp.write("这是使用写入模式 w 写入的内容。")
fp.close()
"w"
模式表示写入模式。如果文件已经存在,会先清空文件中的原有内容,然后再写入新的内容;如果文件不存在,则会创建一个新文件。
读取操作的其他方法
- 逐行读取
readline()
:
fp = open("ceshi.txt", mode="r", encoding="utf-8")
line = fp.readline()
while line:
print(line)
line = fp.readline()
fp.close()
readline()
方法每次从文件中读取一行内容,直到文件末尾。
结果输出
如果代码正常运行,且文件 ceshi.txt
之前没有内容,那么第一次运行代码后,输出结果将是:
大家好!我是python
如果多次运行代码,由于使用的是追加模式 "a"
,每次运行都会在文件末尾添加 "大家好!我是python"
,输出结果会相应地重复显示。
1. 基本文件操作
打开文件
使用 open()
函数,需指定文件路径和模式:
file = open("filename.txt", "r") # 打开文件(默认只读)
# 操作文件...
file.close() # 必须关闭文件
使用 with
语句(推荐)
自动管理文件关闭:
with open("filename.txt", "r") as file:
content = file.read()
# 文件自动关闭
2. 常见文件模式
模式 | 描述 |
---|---|
r | 只读(默认) |
w | 写入(覆盖原有内容) |
a | 追加写入 |
r+ | 读写 |
b | 二进制模式(如 rb , wb ) |
3. 文件读写操作
读取内容
# 读取全部内容
content = file.read()
# 逐行读取
lines = file.readlines()
# 逐行迭代(内存高效)
for line in file:
print(line.strip()) # 去除换行符
写入内容
with open("output.txt", "w") as file:
file.write("Hello, World!\n")
file.writelines(["Line 1\n", "Line 2\n"])
4. 处理不同文件格式
CSV 文件
使用 csv
模块:
import csv
# 读取 CSV
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
# 写入 CSV
with open("output.csv", "w") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 30])
JSON 文件
使用 json
模块:
import json
# 读取 JSON
with open("data.json", "r") as file:
data = json.load(file)
# 写入 JSON
with open("output.json", "w") as file:
json.dump(data, file, indent=4)
5. 高级文件操作
处理大文件
逐行或分块读取,避免内存溢出:
with open("large_file.txt", "r") as file:
for line in file:
process(line) # 逐行处理
文件路径操作
使用 os.path
或 pathlib
:
from pathlib import Path
path = Path("folder/file.txt")
print(path.exists()) # 检查文件是否存在
print(path.parent) # 获取父目录
6. 错误处理
try:
with open("missing_file.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("文件不存在!")
except IOError as e:
print(f"IO错误: {e}")
7. 实战示例
示例1:统计文件行数
with open("data.txt", "r") as file:
line_count = sum(1 for line in file)
print(f"总行数: {line_count}")
示例2:文件内容搜索
search_word = "Python"
with open("data.txt", "r") as file:
for line_num, line in enumerate(file, 1):
if search_word in line:
print(f"第 {line_num} 行找到关键词")
示例3:复制文件
with open("source.txt", "rb") as src, open("dest.txt", "wb") as dst:
dst.write(src.read())
注意事项
-
处理文本文件时,注意编码(如
encoding="utf-8"
)。 -
写入模式
w
会覆盖原文件,需谨慎操作。 -
使用
b
模式处理二进制文件(如图片、视频)。
通过灵活组合这些方法,可以高效完成大多数文件处理任务!