如何从文件中获取数据并在Python中编辑?

时间:2015-12-23 02:31:25

标签: python

我正在尝试用Python创建一个库数据库。我已经完成了大部分工作,但我不知道如何编辑每个图书条目的数据。到目前为止,这是我的代码:

distinct(left(build_date,16))

3 个答案:

答案 0 :(得分:1)

此脚本可以解决您的问题。它使用SQL数据库,因为它更有效,更易于使用。我希望这很容易理解,如果你想了解更多,咨询sqlite3文档不会受到伤害。

在运行之前,请确保.db文件存在,将tablename替换为.db文件中表的名称,标题,作者和ISBN是您的标题。您可能希望将它们全部设置为带有此代码的文本,如果您希望ISBN为整数,则必须进行一些小改动。

#!/usr/bin/python

#imports

import os
import sqlite3

#To find where the script is ran from
script_dir = os.path.dirname(__file__)
#Path relative to the script leading to .db file
rel_path = "database/library.db"
#Starting to work with database
database = sqlite3.connect(os.path.join(script_dir, rel_path), timeout=1)
db = database.cursor()
database.row_factory = sqlite3.Row

def main():
    op = input("What would you like to do? Choose number\nOptions: 1: Insert new book, 2: retrieve book data, 3: edit book data, 4: delete a book:\n")
    if op == "1":
        insertbook()
    elif op == "2":
        retrievebook()
    elif op == "3":
        editbook()
    elif op == "4":
        deletebook()
    else:
        print("Please insert valid choice (1, 2, 3 or 4)")

def insertbook():
    print("You chose to insert a book\n")
    title = input('what is the title of the book?:\n')
    author = input('what is the author of the book?:\n')
    isbn = input('what is the ISBN?:\n')
    db.execute("INSERT INTO tablename VALUES (?, ?, ?)", (title, author, isbn))
    print("Book '%s' added\n" % title)

def retrievebook():
    print("You chose to retieve a book\n")
    title = input('what is the title of the book?:\n')
    db.execute("SELECT * FROM tablename WHERE Title = ?", (title,))
    book = dict(db.fetchone())
    print("Book: %s, Author %s, ISBN %s\n" % (book['Title'], book['Author'], book['ISBN']))

def deletbook():
    print("You chose to delete a book\n")
    title = input('what is the title of the book?:\n')
    c.execute("DELETE FROM tablename WHERE Title=?", (title,))
    database.commit()
    print("Book '%s' deleted\n" % title)

def editbook():
    print("You chose to edit a book\n")
    title = input('what is the title of the book?:\n')
    author = input('what is the author of the book?:\n')
    isbn = input('what is the ISBN?:\n')    
    db.execute("UPDATE tablename SET Author = ? ISBN = ? WHERE Title = ?", (author, isbn, title))
    database.commit()
    print("Book '%s' edited\n" % title)

if __name__ == '__main__':
    main()

如果遇到任何语法错误,我运行python 2.7,所以我可能在python 3打印时出错了。

此外,我不完全确定代码是SQL注入防护,但由于您有删除书籍的命令,我怀疑恶意用户会尝试滥用您的代码。

答案 1 :(得分:0)

为什么不做

之类的事情
elif op == 'edit book data':
    optitle = input('Type the title of the book to be modified: ')

    #the following puts all lines in an array called "lines"
    cb = open(optitle + ".txt", "r")
    lines = cb.readlines()
    cb.close()
    # Now we print each line and ask to enter the new value:
    lines[0] = input('the current title is '+ lines[0] +', please type the new one: ')
    lines[1] = input('the current author is '+ lines[1] +', please type the new one: ')
    # etc....
    #finally we write all back to the file, 
    nb = open(title + ".txt", "w")
    foreach line in lines:
    nb.write(line)
    nb.close()

但是,您应该真正使用数据库,因为@ iScrE4m说。

答案 2 :(得分:0)

您可以创建新文件并为其提供数据:

with open('your_file.txt', 'w') as ef:
    ef.write('Your initial data\n')

您可以打开现有文件并为其提供额外数据:

with open('your_file.txt', 'a') as ef:
    ef.write('Your extra data\n')

顺便说一下,处理文件时使用。它会自动关闭您的文件。