【揭秘Python文件读写操作】这些方法你真的了解吗?

发布时间:2025-04-14 16:04:04

Python 中的文件读写操纵是处理数据的重要方法,它容许顺序与外部数据停止交互,包含从文件中读取数据跟将数据写入文件。控制文件读写操纵对任何 Python 顺序员来说都是必弗成少的。本文将深刻探究 Python 文件读写操纵的各个方面,包含打开文件、读取跟写入数据,以及一些高等技能。

打开文件

在 Python 中,利用 open() 函数打开文件。该函数接收多个参数,其中最重要的两个是文件名跟打开形式。

file = open('example.txt', 'r', encoding='utf-8')
  • file 是你将要操纵的文件东西。
  • 'example.txt' 是文件的道路跟称号。
  • 'r' 表示以只读形式打开文件。
  • encoding='utf-8' 指定了文件的编码格局,默许是 ‘utf-8’。

文件打开形式

以下是一些罕见的文件打开形式:

  • 'r':只读形式,这是默许形式。
  • 'w':写入形式,假如文件已存在,则覆盖它;假如文件不存在,则创建它。
  • 'a':追加形式,在文件的末端追加内容,假如文件不存在,则创建它。
  • 'x':独有创建形式,假如文件已存在,则掉败。
  • 'b':二进制形式,用于读写二进制文件。
  • 't':文本形式,这是默许形式。

读取文件

读取全部文件

with open('example.txt', 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)

逐行读取

with open('example.txt', 'r', encoding='utf-8') as file:
    for line in file:
        print(line, end='')

读取指定字节数

with open('example.txt', 'rb') as file:  # 利用二进制形式读取
    chunk = file.read(100)
    print(chunk)

读取全部行到列表

with open('example.txt', 'r', encoding='utf-8') as file:
    lines = file.readlines()
    for line in lines:
        print(line, end='')

写入文件

写入内容

with open('example.txt', 'w', encoding='utf-8') as file:
    file.write('Hello, world!')

追加内容

with open('example.txt', 'a', encoding='utf-8') as file:
    file.write('Hello, again!')

高等技能

利用高低文管理器

利用 with 语句可能确保文件在操纵实现后被正确封闭。

利用文件指针

seek() 方法可能挪动文件指针的地位。

with open('example.txt', 'r', encoding='utf-8') as file:
    file.seek(5)
    content = file.read(100)
    print(content)

处理异常

利用 try...except 块来处理文件操纵中可能呈现的异常。

try:
    with open('example.txt', 'r', encoding='utf-8') as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print('The file was not found.')

经由过程本文的介绍,你应当对 Python 文件读写操纵有了更深刻的懂得。无论是读取设置文件、处理日记还是停止数据长久化,这些操纵都是弗成或缺的。一直现实跟摸索,你将可能更纯熟地应用这些技能。