0

I want to truncate my file after reading the content of it, but it does not seem to do so and additions to the file are made after the existing content, instead of the beginning of a file.

My code is as follows:

from sys import argv
script, filename = argv
prompt= '??'

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

print("Opening the file...")
target = open(filename,'r+')
print(target.read())
print("I'm going to erase the file now!")


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

print("Now I'm going to ask you 3 lines:")
line1 = input('Line 1: ')
line2 = input('Line 2: ')
line3 = input('Line 3: ')

print("I'm going to write these to the file now!")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally we close the file! Please check and see if the file 
    has been modified!")
target.close()         
1
  • 1
    Doesn't .truncate remove everything after the current position? In your case, as you just .read everything, there's nothing to truncate. Commented Mar 2, 2018 at 8:12

2 Answers 2

4

To truncate a file to zero bytes you can just open it with write access, no need to actually write anything. It can be done simply:

with open(filename, 'w'): pass

However, using your code you need to reset the current file position to beginning of file before the truncate:

....
print("Truncating the file. Goodbye!")  
target.seek(0)                            # <<< Add this line
target.truncate() 
....

Example run (script is gash.py):

$ echo -e 'x\ny\nz\n' > gash.txt
$ python3 gash.py gash.txt
We're going to erase 'gash.txt'.
If you don't want that, hit CTRL-C.
If you do want it, hit ENTER.
??
Opening the file...
x
y
z


I'm going to erase the file now!
Truncating the file. Goodbye!
Now I'm going to ask you 3 lines:
Line 1: one
Line 2: two
Line 3: three
I'm going to write these to the file now!
And finally we close the file! Please check and see if the file has been modified!
$ cat gash.txt
one
two
three
$
Sign up to request clarification or add additional context in comments.

4 Comments

It truncates the file now, but it doesn't print what was in the file initially after opening the file.
Are you sure there was something in the file initially? It works for me. You should have only added that single target.seek(0) line, perhaps you added both methods?
Yes. Checked to see that there was something in the file. That was the only line I added. Doesn't make sense to me too. :/
Did you run the script to completion before checking the file contents? The file will appear to be empty until the buffers are flushed, usually when the file is closed.
0

To Truncate just write:

f = open('filename', 'w')
f.close()

2 Comments

There is no need for the f.write() or the f.truncate(), the open with write access will truncate the file by itself.
Good Point @cdarke. Made the changes.

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.