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

How do I update an existing text file in Python?

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

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

我把它排序成一个列表来得到:

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

我使用的代码是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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文件,使其包含当前列表。如何在不导入任何库的情况下完成此操作?

事先谢谢。

更新:我尝试这样做:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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()

但我得到了这个错误:

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

我做错什么了?


如果您只想对文件中的行进行排序,则不需要拆分行或将其剥离。这只需要连接它们并在以后再次添加正确的行分隔符。

试试这个;

1
2
3
4
5
with open('books.txt') as books:
    lines = books.readlines()
lines.sort()
with open('books.txt', 'w') as sortedbooks:
    sortedbooks.writelines(lines)


试试这个:

1
2
3
4
5
6
7
8
9
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('
'
.join([','.join(line) for line in l]))