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?

4
  • Have you tried opening the file in write/append mode instead of only read mode? Commented May 7, 2016 at 14:21
  • No, I haven't. Could you please explain what you mean? I'm new to Python. Commented May 7, 2016 at 14:23
  • Suggest you read this: docs.python.org/3/tutorial/… Commented May 7, 2016 at 14:26
  • 1
    @SammieG: Why don't you just use the csv module? It comes with Python. Commented May 7, 2016 at 14:27

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

3 Comments

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 stackoverflow.com/questions/2333872/… )!
@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.
Correct, it's a mess. Still, many platforms allow file locking. For anyone interested in the topic see: stackoverflow.com/questions/489861/locking-a-file-in-python
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]))

2 Comments

(though this works, the file may remain open until the interpreter exits; files should always be explicitly closed in python, preferably using the with syntax)
@spectras, thanks for the correction! I've updated my answer correspondingly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.