Python 不会写回文件修改行

问题描述 投票:0回答:2

我有这个函数,应该以字符串格式修改 int 并将更改写回文件。我确信传递给函数的 isbn 是正确的。

这是我的功能:

def decrementBookUnits(isbn):
    with open('books.txt', 'r') as booksFile:
        content = booksFile.readlines()
        for line in content:
            if str(isbn) in line:
                wordList = line.split(' -- ')
                wordList2 = wordList[6].split(':')
                if int(wordList2[1]) == isbn:
                    wordList3 = wordList[5].split(':')
                    wordList[1] = wordList3[1].replace('3', '666')
                    with open('books.txt', 'w') as booksFile:
                        booksFile.writelines(content)

这是 books.txt 文件的上下文:

    ID:0 -- Title:ff -- Author:dfdf -- Editor:df -- YearOfRelease:2000 -- NumberOfUnits:3 -- ISBN:123
    ID:01 -- Title:title -- Author:author -- Editor:editor -- YearOfRelease:2003 -- NumberOfUnits:1 -- ISBN:1234
    ID:03 -- Title:title -- Author:author -- Editor:editor -- YearOfRelease:2000 -- NumberOfUnits:0 -- ISBN:321
    ID:04 -- Title:title -- Author:author -- Editor:editor -- YearOfRelease:2000 -- NumberOfUnits:4 -- ISBN:44
    ID:05 -- Title:title -- Author:author -- Editor:editor -- YearOfRelease:20055 -- NumberOfUnits:3 -- ISBN:33
    ID:06 -- Title:title -- Author:author -- Editor:editor -- YearOfRelease:2006 -- NumberOfUnits:6 -- ISBN:70
    ID:07 -- Title:title -- Author:author -- Editor:editor -- YearOfRelease:2011 -- NumberOfUnits:7 -- ISBN:54
    ID:08 -- Title:title -- Author:author -- Editor:editor -- YearOfRelease:2000 -- NumberOfUnits:4 -- ISBN:44
    ID:09 -- Title:title -- Author:author -- Editor:editor -- YearOfRelease:20055 -- NumberOfUnits:3 -- ISBN:33
    ID:10 -- Title:title -- Author:author -- Editor:editor -- YearOfRelease:2006 -- NumberOfUnits:6 -- ISBN:70
    ID:11 -- Title:title -- Author:author -- Editor:editor -- YearOfRelease:2011 -- NumberOfUnits:7 -- ISBN:54
    ID:12 -- Title:hhh -- Author:hhh -- Editor:hh -- YearOfRelease:2004 -- NumberOfUnits:2 -- ISBN:77

例如,传递的 isbn 值为 33,该函数应该将 NumberOfUnits 从 3 更改为 666,但事实并非如此。预先感谢。

python python-3.x file-io
2个回答
0
投票

如何更新与给定变量匹配的行,写出到不同的txt文件

def decrementBookUnits(isbn):
    updated_lines = []
    with open('books.txt', 'r') as booksFile:
        content = booksFile.readlines()
    for line in content:
        if str(isbn) in line.lower():
            parts = line.split(' -- ')
            quantity_part = parts[5].split(':')
            quantity_part[1] = quantity_part[1].replace('3', '666')
            parts[5] = ':'.join(quantity_part)
            line = ' -- '.join(parts)
            updated_lines.append(line)
    with open('books2.txt', 'w') as booksFile2:
        booksFile2.writelines(updated_lines)
decrementBookUnits(33)

0
投票

正如评论中提到的,您的代码存在一些更大的问题。首先,写入已打开的文件;可以通过取消缩进代码轻松纠正的问题。其次,更大的问题是你对变量如何工作的假设。第二个问题更难解决。

这是对代码的重写,将函数分解为三个操作:

  1. 用于打开文件并将内容转换为字典对象列表的函数。这将使您想要构建的任何其他功能更轻松地处理这些数据。

  2. 专门用于减少这个新书籍对象中的特定 ISBN 的函数。如果您愿意,将其分离为单个函数有助于划分代码,并允许您在在此对象内打开书籍文件时减少更多 ISBN。

  3. 将新书籍对象写入文件的函数,其格式与读取的格式相同。


def getBooks(file):
    """
    The function `getBooks` reads a file, splits its content into lines, and then splits each line into
    key-value pairs to create a list of dictionaries representing books.
    
    :param file: The `file` parameter is the name or path of the file that contains the book information
    :return: a list of dictionaries, where each dictionary represents a book with key-value pairs for
    its attributes.
    """
    #open the file
    with open(file, 'r') as booksFile:
        content = booksFile.read().splitlines()
    
    #split each line to a list
    lines=[line.split(' -- ') for line in content]
    
    #turn entries in each line into a key:val pair for a dictionary
    books=[dict(entry.split(':') for entry in line) for line in lines]
    
    return books

def decrementBookUnits(books,isbn):   
    """
    The function `decrementBookUnits` takes a list of books and an ISBN number, and updates the ISBN of
    the book with the given ISBN number to '666'.
    
    :param books: A list of dictionaries representing books. Each dictionary contains information about
    a book, including its ISBN
    :param isbn: The `isbn` parameter is the ISBN (International Standard Book Number) of the book that
    you want to decrement the units for
    :return: the updated list of books after decrementing the units of a book with the given ISBN.
    """
    #iterate through the books list 
    for idx, entry in enumerate(books):
        #check if this entry has our isbn
        if entry['ISBN'] == str(isbn):
            #update the books entry's ISBN by updating the 
            # actual `books` object directly using the idx
            books[idx]['ISBN'] = '666'  
    return books

def writeBooks(books, file):
    """
    The function `writeBooks` takes a list of books and a file name as input, opens the file, iterates
    through the books, and writes each book entry to the file in a specific format.
    
    :param books: The "books" parameter is a list of dictionaries. Each dictionary represents a book and
    contains key-value pairs for different attributes of the book, such as title, author, genre, etc
    :param file: The `file` parameter is the name or path of the file where the books will be written
    """
    #Open file, iterate entries, and write back out
    with open(file, 'w') as booksFile:
        for entry in books:
            booksFile.writelines(' -- '.join(['='.join([k,v]) for k,v in entry.items()]) + '\n')

#get the contents of the book an object
# defined by the function
books=getBooks('books.txt')

#see what this looks like
print(books) 

#decrement books with an ISBN of 33
books=decrementBookUnits(books,33)

#write our books object back out to a file
# using a new file so this can be run over 
# and over again.
writeBooks(books,'books2.txt')
© www.soinside.com 2019 - 2024. All rights reserved.