文件操作实战


使用文件操作将图书管理系统进行改造(将数据保存到文件)

import os


def create_book():
    file = open('books.txt', 'a', encoding='utf-8')
    file.close()


def main():
    while True:
        print('-' * 50)
        print('欢迎使用图书管理系统!')
        print('-' * 50)
        print('增加图书【1】删除图书【2】修改图书【3】查看图书【4】')
        print('-' * 50)
        num = input('请输入数字指令:')
        if num == '1':
            add()
        elif num == '2':
            delete()
        elif num == '3':
            modify()
        elif num == '4':
            search()
        else:
            print('您的输入错误!')


def add():
    book = input('请您输入书名:')
    with open('books.txt', 'a', encoding='utf-8') as file:
        file.write(book + '\n')
        print(f'{book}增加成功!')


def delete():
    book = input('请您输入需要删除的书名:')
    with open('books.txt', 'r', encoding='utf-8') as file:
        books = file.readlines()
    if book + '\n' in books:
        books.remove(book + '\n')
        with open('books.txt', 'w', encoding='utf-8') as file:
            file.writelines(books)
            print(f'{book}删除成功!')
    else:
        print('您输入的书名不存在!')


def modify():
    book = input('请您输入需要修改的书名:')
    with open('books.txt', 'r', encoding='utf-8') as file:
        books = file.readlines()
    if book + '\n' in books:
        newbook = input('请您输入新的书名:')
        books[books.index(book + '\n')] = newbook + '\n'
        with open('books.txt', 'w', encoding='utf-8') as file:
            file.writelines(books)
        print(f'{book}已修改为{newbook}!')
    else:
        print('您输入的书名不存在!')


def search():
    size = os.path.getsize('books.txt')
    if size == 0:
        print('目前没有图书!')
    else:
        with open('books.txt', 'r', encoding='utf-8') as file:
            for book in file:
                print(f'书名:{book}')


create_book()
main()

results matching ""

    No results matching ""