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()         
Cong Ma
  • 10,692
  • 3
  • 31
  • 47
Rhagavan
  • 9
  • 1
  • 2
  • 1
    Doesn't .truncate remove everything *after* the current position? In your case, as you just .read everything, there's nothing to truncate. – jonrsharpe Mar 02 '18 at 08:12

2 Answers2

1

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
$
cdarke
  • 42,728
  • 8
  • 80
  • 84
  • It truncates the file now, but it doesn't print what was in the file initially after opening the file. – Rhagavan Mar 02 '18 at 09:04
  • 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? – cdarke Mar 02 '18 at 09:06
  • 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. :/ – Rhagavan Mar 02 '18 at 09:10
  • 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. – cdarke Mar 02 '18 at 11:32
0

To Truncate just write:

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