如何更新 Python 中的现有文本文件?

How do I update an existing text file in Python?

我有一个 books.txt 文件,其中包含如下书名、作者和价格:

The Hunger Games,Suzanne Collins,12.97
The Fault In Our Stars,John Green,11.76
The Notebook,Nicholas Sparks,11.39

我把它整理成一个列表列表得到这个:

[[The Hunger Games, Suzanne Collins, 12.97], [The Fault In Our Stars, John Green, 11.76], [The Notebook, Nicholas Sparks, 11.39]]

我使用的代码是:

def booksDatabase():
        for line in infile:
            line = line.rstrip().split(",")
            line[2] = float(line[2])
            table.append(line)


infile = open("books.txt")

table = []

booksDatabase() 

infile.close()

我想更新 .txt 文件,以便它包含当前的列表列表。在不导入任何库的情况下如何做到这一点?

提前致谢。

更新: 我试过这样做:

def booksDatabase():
        for line in infile:
            line = line.rstrip().split(",")
            line[2] = float(line[2])
            table.append(line)
            outfile.write(line)

infile = open("books.txt")
outfile = open("books.txt", 'w')

table = []

booksDatabase() 

infile.close()

但是我得到了这个错误:

    outfile.write(line)
TypeError: write() argument must be str, not list

我做错了什么?

试试这个:

In [354]: l
Out[354]:
[['The Hunger Games', 'Suzanne Collins', '12.97'],
 ['The Fault In Our Stars', 'John Green', '11.76'],
 ['The Notebook', 'Nicholas Sparks', '11.39']]

with open('d:/temp/a.txt', 'w') as f:
    f.write('\n'.join([','.join(line) for line in l]))

如果您只想对文件中的行进行排序,则无需拆分行或剥离行。那只会使有必要加入他们并稍后再次添加正确的行分隔符。

所以试试这个;

with open('books.txt') as books:
    lines = books.readlines()
lines.sort()
with open('books.txt', 'w') as sortedbooks:
    sortedbooks.writelines(lines)