Reputation: 9
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()
Upvotes: 0
Views: 6236
Reputation: 44354
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
$
Upvotes: 4