像C语言一样用结构体方式访问文本文件
回答
收藏

像C语言一样用结构体方式访问文本文件

金属车身系统产品线工艺部_贺轶龙
2023-08-07 13:08·浏览量:229
金属车身系统产品线工艺部_贺轶龙
影刀中级开发者
发布于 2023-08-07 13:08229浏览

import os

# 定义自定义结构体类

class Record:

    def __init__(self, id, name, age):

        self.id = id

        self.name = name

        self.age = age


# 定义文件路径

file_path = 'records.txt'


# 增加记录

def add_record(record):

    with open(file_path, 'a') as file:

        file.write(f"{record.id},{record.name},{record.age}\n")


# 删除记录

def delete_record(record_id):

    records = []

    with open(file_path, 'r') as file:

        for line in file:

            fields = line.strip().split(',')

            if int(fields[0]) != record_id:

                records.append(Record(int(fields[0]), fields[1], int(fields[2])))


    with open(file_path, 'w') as file:

        for record in records:

            file.write(f"{record.id},{record.name},{record.age}\n")


# 访问指定记录

def get_record(record_id):

    with open(file_path, 'r') as file:

        for line in file:

            fields = line.strip().split(',')

            if int(fields[0]) == record_id:

                return Record(int(fields[0]), fields[1], int(fields[2]))


# 查找记录

def find_record(name):

    found_records = []

    with open(file_path, 'r') as file:

        for line in file:

            fields = line.strip().split(',')

            if fields[1].lower() == name.lower():

                found_records.append(Record(int(fields[0]), fields[1], int(fields[2])))


    return found_records


# 示例使用

record1 = Record(1, 'John', 25)

record2 = Record(2, 'Alice', 30)

record3 = Record(3, 'Bob', 35)


# 增加记录

add_record(record1)

add_record(record2)

add_record(record3)


# 访问指定记录

record = get_record(2)

if record:

    print(f"Record found - ID: {record.id}, Name: {record.name}, Age: {record.age}")

else:

    print("Record not found")


# 删除记录

delete_record(1)


# 查找记录

found_records = find_record('Bob')

if found_records:

    for record in found_records:

        print(f"Record found - ID: {record.id}, Name: {record.name}, Age: {record.age}")

else:

    print("Records not found")

收藏
全部回答1
最新
发布回答
回答