2

I'm currently working my way through Learning Python the Hard Way and I've got a little bit stuck on a modification I wanted to make on exercise 16.

So, this is my code:

from sys import argv

script, filename = argv

print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename,'w+')

#Print contents ## WHY WONT THIS WORK??
print "This was inside your file %r:" % filename
target.seek(0)
print target.read()

This is where my problem is. The print function above does not print the file, rather just gives a blank line. The rest of the code follows below and as you will see there is a second print that works fine.

print "Truncating the file. Goodbye!"
target.truncate()

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."
target.write(("\n%s\n%s\n%s\n") % (line1, line2, line3))

#This print does work
target.seek(0)
print target.read()

print "And finally, we close it."
target.close()

What am I doing wrong here?

Nick is tired
  • 6,860
  • 20
  • 39
  • 51
Dimlimber
  • 23
  • 2
  • 2
    Is there a specific reason to use [Python2.x as a beginner](https://pythonclock.org/)? And FWIW, SOpython is [not really fond of Learn Python The Hard Way](https://sopython.com/wiki/What_tutorial_should_I_read%3F). – Mr. T Mar 02 '18 at 11:29

1 Answers1

3

When you open a file in a write mode ('w' or 'w+'), python will truncate the file (or create it if it doesn't already exist).

Instead open the file in read/append mode for reading and writing ('r+' or 'a+'), this won't truncate the file and still allow you to both read and write to it.

This post provides a useful flow chart which shows which open modes should be used under what circumstances.


Because in your initial code the file was already empty, your truncate didn't do anything.

Because of this, when you've updated your code to use 'a+' or 'r+' you'll need to update your truncate.

truncate(size) will truncate the file to the file to the cursors current position (or at most size if it is present), so before truncating move the cursor to the beginning for the file again with target.seek(0).

Nick is tired
  • 6,860
  • 20
  • 39
  • 51
  • Thanks mate, does this mean that in my original script this: print "Truncating the file. Goodbye!" target.truncate()
    wasn't actually necessary? When changing it to 'r+' or 'a+', while the $print target.read() function works, the truncate no longer does.. Is there a way to have both? ie read before truncate?
    – Dimlimber Mar 02 '18 at 11:45
  • Makes sense - good to know truncate also uses a cursor position. thanks. – Dimlimber Mar 02 '18 at 11:50