0

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?

potatofeast
  • 27
  • 1
  • 1
  • 10

2 Answers2

1

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)
Roland Smith
  • 42,427
  • 3
  • 64
  • 94
  • Although this is a very basic question/anwser just a word of warning: This setup is not atomic i.e. if books.txt gets changed by another process between the read and write lines you will loose data (see https://stackoverflow.com/questions/2333872/atomic-writing-to-file-with-python )! – Oliver Zendel Sep 18 '17 at 09:32
  • @OliverZendel You are correct, but given the use case I don't think that this is an issue here. And unless the operating system support (strict, not advisory) locking, you can never have a *guarantee* that a file is not overwritten. – Roland Smith Sep 18 '17 at 17:03
  • Correct, it's a mess. Still, many platforms allow file locking. For anyone interested in the topic see: https://stackoverflow.com/questions/489861/locking-a-file-in-python – Oliver Zendel Sep 19 '17 at 08:48
0

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]))
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419