gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:37:36 25 4
gpt4 key购买 nike

我有一个 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

我做错了什么?

最佳答案

如果您只想对文件中的行进行排序,则无需分割行或剥离它们。这只需要加入它们并稍后再次添加正确的行分隔符。

所以试试这个;

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

关于python - 如何在 Python 中更新现有文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37089641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com