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

时间:2016-05-07 14:19:13

标签: python python-3.x file-writing

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

我做错了什么?

2 个答案:

答案 0 :(得分:1)

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

所以试试这个;

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

答案 1 :(得分:0)

试试这个:

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]))