python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python文件读写操作

Python文件读写操作详解

作者:程序小武

在 Python 中,文件操作非常常见,可以通过内建的 open() 函数进行文件的读取、写入、创建等操作,理解文件操作的模式和 with 语句对于确保代码的简洁性和效率至关重要,本文给大家从基础到实战详细介绍了Python文件的读写操作,需要的朋友可以参考下

Python 文件的读写操作

1. 打开文件 open()

在 Python 中,文件操作的基本函数是 open(),它用于打开一个文件并返回一个文件对象,通过该对象可以对文件进行读取和写入操作。open()函数有两个常用参数:

open(file, mode)

1.1 常见的打开模式

模式说明
r只读模式(默认)。文件必须存在,否则抛出 FileNotFoundError。
w写模式。文件如果存在则覆盖,不存在则创建新文件。
a追加模式。文件若存在,则在文件末尾追加内容;若文件不存在,创建新文件。
x排他性创建模式。若文件已存在,抛出 FileExistsError。
b二进制模式,用于处理非文本文件,如图片等。
t文本模式(默认)。用于读取或写入文本文件。
r+读写模式。文件必须存在,可以同时进行读取和写入。
w+写读模式。文件如果存在会被覆盖,不存在则创建新文件。
a+追加读写模式。可以读写文件,文件若不存在则创建新文件。

1.2 示例

假如example.txt的文件内容为:hello world为举例

# 只读模式打开文件
file = open('example.txt', 'r')
print(file) 
print(file.read())  #会输出example.txt的文件内容
file.close() #关闭文件

输出:

<_io.TextIOWrapper name='example.txt' mode='r' encoding='cp65001'>
hello world

1.3 代码及输出解释:

2. 使用 with 语句

with 语句提供了一个更简洁的方式来管理文件资源。使用 with 语句时,Python 会自动管理文件的打开和关闭。无论文件操作是否成功,文件都会在操作结束后自动关闭。

2.1 with 语句的优点

语法:

with open('文件路径', '模式') as 打开后赋值的变量名:
    空四格(写打开文件后进行的操作代码)

2.2 示例

with open('example.txt', 'r') as file:
    content = file.read()
    print(content) #输出hello world
file=open('example.txt', 'r')

3. 读取文件内容

Python 提供了几种方法来读取文件内容:

hello wrold
hello wrold
hello wrold
hello wrold
hello wrold

3.1 read() 示例 返回全部内容

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() 示例 每次返回第一行内容

with open('example.txt', 'r') as file:
    line = file.readline()  # 读取第一行
    print(line)

输出示例:

hello wrold

3.3 readlines() 示例 以列表的形式返回全部数据

with open('example.txt', 'r') as file:
    lines = file.readlines()  # 读取所有行,返回一个列表
    print(lines)

输出示例:

['hello wrold\n', 'hello wrold\n', 'hello wrold\n', 'hello wrold\n', 'hello wrold']

4. 写入文件

文件的写入操作使用 write()writelines() 方法:

4.1 write() 示例 将字符串写入文件

with open('output.txt', 'w') as file:  #w模式文件如果存在则覆盖,不存在则创建新文件
    file.write('Hello, Python!')

output.txt文件内容:

Hello, Python!

4.2 writelines() 示例 将字符串列表写入文件

lines = ['Hello, Python!\n', 'This is another line.\n']

with open('output.txt', 'w') as file:
    file.writelines(lines)

output.txt文件内容(因添加\n故而换行):

Hello, Python!
This is another line.

4.3 追加写入

with open('output.txt', 'a') as file:
    file.write('Appending a new line.')

output.txt文件内容:

Hello, Python!This is another line.
Appending a new line.

PS:如果写入的内容需要换行可以在字符串里面添加\n

开头添加换行例如:file.write('\nAppending a new line.')

4.4 二进制写模式 wb

with open('output.jpg', 'wb') as file:
        file.write(content)  # 将content内容以二进制形式写入

4.5 二进制追加模式 ab

with open('output.jpg', 'ab') as file:
        file.write(content)  # 将content新内容追加到文件末尾

5. 完整案例:日志文件管理

假设我们有一个日志文件,每次程序运行时都会记录一个日志条目,记录程序的执行情况。下面是一个完整的示例:

# 写入日志
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())

解释:

总结

通过这些基础的文件操作,你可以高效地处理文件读写任务,同时确保代码简洁且安全。

以上就是Python文件读写操作详解的详细内容,更多关于Python文件读写操作的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文