Python 文件的读写操作
在 Python 中,文件操作非常常见,可以通过内建的 open()
函数进行文件的读取、写入、创建等操作。理解文件操作的模式和 with
语句对于确保代码的简洁性和效率至关重要。
1. 打开文件 open()
在 Python 中,文件操作的基本函数是 open()
,它用于打开一个文件并返回一个文件对象,通过该对象可以对文件进行读取和写入操作。open()
函数有两个常用参数:
file
:表示文件的路径,可以是相对路径或绝对路径。mode
:表示文件打开的模式,决定了文件的操作方式。语法
:
scss
open(file, mode)
1.1 常见的打开模式
模式 | 说明 |
---|---|
r |
只读模式(默认)。文件必须存在,否则抛出 FileNotFoundError 。 |
w |
写模式。文件如果存在则覆盖,不存在则创建新文件。 |
a |
追加模式。文件若存在,则在文件末尾追加内容;若文件不存在,创建新文件。 |
x |
排他性创建模式。若文件已存在,抛出 FileExistsError 。 |
b |
二进制模式,用于处理非文本文件,如图片等。 |
t |
文本模式(默认)。用于读取或写入文本文件。 |
r+ |
读写模式。文件必须存在,可以同时进行读取和写入。 |
w+ |
写读模式。文件如果存在会被覆盖,不存在则创建新文件。 |
a+ |
追加读写模式。可以读写文件,文件若不存在则创建新文件。 |
1.2 示例
假如example.txt的文件内容为:hello world
为举例
python
# 只读模式打开文件
file = open('example.txt', 'r')
print(file)
print(file.read()) #会输出example.txt的文件内容
file.close() #关闭文件
输出:
ini
<_io.TextIOWrapper name='example.txt' mode='r' encoding='cp65001'>
hello world
1.3代码及输出解释:
open('example.txt', 'r')
:打开了一个名为example.txt
的文件,以只读模式 ('r'
) 打开file.read()
:在file
对象上调用read()
方法,用于读取文件的所有内容file.close()
在file对象上调用close()
方法,用于关闭文件,是为了确保资源被释放<_io.TextIOWrapper ...>
:TextIOWrapper
是 Python 内部用于处理文本文件的类name='example.txt'
:这是文件对象的名称,表示文件路径。mode='r'
:以只读模式r
打开文件(即只能读取文件内容,不能修改)。encoding='cp65001'
:这是文件的编码方式为cp65001
(cp65001
是 UTF-8 编码的一个别名)
2. 使用 with
语句
with
语句提供了一个更简洁的方式来管理文件资源。使用 with
语句时,Python 会自动管理文件的打开和关闭。无论文件操作是否成功,文件都会在操作结束后自动关闭。
2.1 with
语句的优点
- 自动管理资源,避免忘记关闭文件。
- 即使发生异常,也能保证文件被正确关闭。
- 代码更简洁。
语法:
python
with open('文件路径', '模式') as 打开后赋值的变量名:
空四格(写打开文件后进行的操作代码)
2.2 示例
python
with open('example.txt', 'r') as file:
content = file.read()
print(content) #输出hello world
as file
:文件对象赋值给变量file
;可以理解为使用open
函数这样写:
python
file=open('example.txt', 'r')
- 在上面的例子中,文件在
with
语句结束后会自动关闭文件。
3. 读取文件内容
Python 提供了几种方法来读取文件内容:
-
read()
:读取整个文件的内容,返回一个字符串。 -
readline()
:逐行读取文件,每次返回一行内容。 -
readlines()
:读取文件的所有行并返回一个列表。 -
假设
example.txt
的文件内容为:hello wrold
hello wrold
hello wrold
hello wrold
hello wrold
3.1 read()
示例 返回全部内容
python
with open('example.txt', 'r') as file:
content = file.read() # 读取整个文件
print(content)
输出示例:
hello wrold
hello wrold
hello wrold
hello wrold
hello wrold
3.2 readline()
示例 每次返回第一行内容
python
with open('example.txt', 'r') as file:
line = file.readline() # 读取第一行
print(line)
输出示例:
hello wrold
3.3 readlines()
示例 以列表的形式返回全部数据
python
with open('example.txt', 'r') as file:
lines = file.readlines() # 读取所有行,返回一个列表
print(lines)
输出示例:
css
['hello wrold\n', 'hello wrold\n', 'hello wrold\n', 'hello wrold\n', 'hello wrold']
4. 写入文件
文件的写入操作使用 write()
或 writelines()
方法:
write()
:将字符串写入文件,如果文件存在则覆盖。writelines()
:将字符串列表写入文件,只能字符串类型的数据列表,否则报错
4.1 write()
示例 将字符串写入文件
python
with open('output.txt', 'w') as file: #w模式文件如果存在则覆盖,不存在则创建新文件
file.write('Hello, Python!')
output.txt
文件内容:
Hello, Python!
4.2 writelines()
示例 将字符串列表写入文件
python
lines = ['Hello, Python!\n', 'This is another line.\n']
with open('output.txt', 'w') as file:
file.writelines(lines)
output.txt
文件内容(因添加\n
故而换行):
arduino
Hello, Python!
This is another line.
4.3 追加写入
python
with open('output.txt', 'a') as file:
file.write('Appending a new line.')
output.txt
文件内容:
arduino
Hello, Python!This is another line.
Appending a new line.
PS:如果写入的内容需要换行可以在字符串里面添加\n
开头添加换行例如:file.write('\nAppending a new line.')
4.4 二进制写模式 wb
- 含义:以二进制模式写入文件。如果文件存在,内容会被覆盖;如果文件不存在,则创建文件
- 用途:适用于写入非文本文件,如图像、音频文件等
python
with open('output.jpg', 'wb') as file:
file.write(content) # 将content内容以二进制形式写入
4.4 二进制追加模式 ab
- 含义:以二进制模式向文件追加内容。如文件不存在,会创建文件;反之会添加到文件的末尾
- 用途:适用于不断向文件中追加数据(二进制数据等)容易出问题,一般wb即可
python
with open('output.jpg', 'ab') as file:
file.write(content) # 将content新内容追加到文件末尾
5. 完整案例:日志文件管理
假设我们有一个日志文件,每次程序运行时都会记录一个日志条目,记录程序的执行情况。下面是一个完整的示例:
python
# 写入日志
def write_log(log_message):
with open('logfile.txt', 'a') as log_file:
log_file.write(log_message + '\n')
# 读取日志
def read_logs():
with open('logfile.txt', 'r') as log_file:
logs = log_file.readlines()
return logs
# 示例用法
write_log('日志数据1')
write_log('日志数据2')
# 读取并显示日志
logs = read_logs()
print("Logs:")
for log in logs:
print(log.strip())
解释:
- write_log函数 :将日志信息追加到
logfile.txt
文件中。 - read_logs函数 :读取
logfile.txt
中的所有日志,并返回列表。 - 通过运行程序,生成三条日志,并将其打印出来。
7. 总结
- 文件操作模式 :选择合适的模式(如
r
、w
、a
等)进行文件的读取或写入。 with
语句:提供了简洁且安全的文件操作方式,自动处理文件的关闭。- 文件读取与写入 :掌握
read()
、readline()
、write()
、writelines()
等方法,灵活处理文件内容。
通过这些基础的文件操作,你可以高效地处理文件读写任务,同时确保代码简洁且安全。