potatofeast
potatofeast

Reputation: 27

How do I update an existing text file in Python?

I've got a books.txt file which contains book titles, authors and prices as follows:

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

I sorted it into a list of lists to get this:

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

The code I used is:

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

And I'd like to update the .txt file so that it contains the current list of lists. How do I do that without importing any libraries?

Thanks in advance.

Update: I tried doing this:

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

But I got this error:

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

What am I doing wrong?

Upvotes: 0

Views: 22784

Answers (2)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210972

try this:

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

Upvotes: 0

Roland Smith
Roland Smith

Reputation: 43533

If you just want to sort the lines in the file, there is no need to split the lines or to strip them. That would only make it necessary to join them and add the correct line separator again later.

So try this;

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

Upvotes: 1

Related Questions