Python 文件读写

person smartzeng    watch_later 2024-08-14 20:15:24
visibility 184    class Python    bookmark 专栏

Python 文件读写

文件读写操作是 Python 中非常常见的任务,涉及到如何打开、读取、写入文件,以及如何安全地关闭文件。下面我们将介绍这些操作,并通过一个简单的通讯录管理系统项目来展示这些操作的应用。

1. 打开文件

在 Python 中,使用 open() 函数可以打开文件。该函数返回一个文件对象,后续操作都基于这个对象。open() 函数的基本语法如下:

file = open('filename', 'mode')
  • filename:要打开的文件名或路径。
  • mode:文件打开模式,常见的模式包括:
    • 'r':以只读模式打开文件(默认)。
    • 'w':以写入模式打开文件,会覆盖原文件。
    • 'a':以追加模式打开文件,在文件末尾追加内容。
    • 'b':以二进制模式打开文件。

2. 读取文件

读取文件内容有几种方式:

  • read():读取文件的全部内容。
  • readline():按行读取文件。
  • readlines():读取所有行,并返回列表。
# 读取整个文件内容
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

# 按行读取文件
with open('example.txt', 'r') as file:
    for line in file:
        print(line.strip())

3. 写入文件

写入文件时,可以使用 write() 方法或 writelines() 方法。

# 写入单行
with open('example.txt', 'w') as file:
    file.write('Hello, World!\n')

# 写入多行
lines = ['First line\n', 'Second line\n', 'Third line\n']
with open('example.txt', 'w') as file:
    file.writelines(lines)

4. 文件的关闭与上下文管理

使用 open() 函数打开文件后,必须调用 close() 方法来关闭文件,以释放资源。不过,使用 with 语句可以更方便地管理文件对象,不需要手动关闭文件,即使在发生异常时也能自动关闭文件。

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

5. 小型项目:通讯录管理系统

下面我们通过一个简单的通讯录管理系统,来实践文件的增删改查操作。

功能描述:

  • 添加联系人:将联系人信息存储到文件中。
  • 删除联系人:从文件中删除指定的联系人信息。
  • 更新联系人:修改文件中指定联系人的信息。
  • 查询联系人:从文件中查询并显示指定的联系人信息。
# 通讯录管理系统
import os

CONTACTS_FILE = 'contacts.txt'

def add_contact(name, phone):
    with open(CONTACTS_FILE, 'a') as file:
        file.write(f'{name},{phone}\n')
    print(f'Added contact: {name} - {phone}')

def delete_contact(name):
    if not os.path.exists(CONTACTS_FILE):
        print("No contacts found.")
        return
  
    updated_lines = []
    found = False
    with open(CONTACTS_FILE, 'r') as file:
        lines = file.readlines()
        for line in lines:
            contact_name, _ = line.strip().split(',')
            if contact_name != name:
                updated_lines.append(line)
            else:
                found = True

    if found:
        with open(CONTACTS_FILE, 'w') as file:
            file.writelines(updated_lines)
        print(f'Deleted contact: {name}')
    else:
        print(f'Contact {name} not found.')

def update_contact(name, new_phone):
    if not os.path.exists(CONTACTS_FILE):
        print("No contacts found.")
        return
  
    updated_lines = []
    found = False
    with open(CONTACTS_FILE, 'r') as file:
        lines = file.readlines()
        for line in lines:
            contact_name, _ = line.strip().split(',')
            if contact_name == name:
                updated_lines.append(f'{name},{new_phone}\n')
                found = True
            else:
                updated_lines.append(line)

    if found:
        with open(CONTACTS_FILE, 'w') as file:
            file.writelines(updated_lines)
        print(f'Updated contact: {name} - {new_phone}')
    else:
        print(f'Contact {name} not found.')

def search_contact(name):
    if not os.path.exists(CONTACTS_FILE):
        print("No contacts found.")
        return

    with open(CONTACTS_FILE, 'r') as file:
        found = False
        for line in file:
            contact_name, phone = line.strip().split(',')
            if contact_name == name:
                print(f'Found contact: {name} - {phone}')
                found = True
                break
        if not found:
            print(f'Contact {name} not found.')

def display_contacts():
    if not os.path.exists(CONTACTS_FILE):
        print("No contacts found.")
        return
  
    with open(CONTACTS_FILE, 'r') as file:
        print("All contacts:")
        for line in file:
            name, phone = line.strip().split(',')
            print(f'{name} - {phone}')

# 示例操作
add_contact('Alice', '1234567890')
add_contact('Bob', '0987654321')
display_contacts()

search_contact('Alice')
update_contact('Alice', '1112223333')
display_contacts()

delete_contact('Bob')
display_contacts()

项目说明:

  • 添加联系人add_contact 函数将联系人信息(名字和电话)以逗号分隔的形式追加到文件中。
  • 删除联系人delete_contact 函数读取文件内容,删除指定的联系人后重新写入文件。
  • 更新联系人update_contact 函数在文件中找到指定的联系人,更新其信息并保存。
  • 查询联系人search_contact 函数根据联系人名字在文件中搜索并显示对应信息。

通过这个小项目,涵盖了基本的文件读写操作,包括如何安全地管理文件、如何处理文件中的数据等。

评论区
评论列表
menu