I'm unable to get this exercise running properly:
from sys import argv
script, filename = argv
print(f"We're going to erase {filename}.")
print("If you don't want that, CRTL-C (^C).")
print("If you do want that, hit RETURN.")
input("?")
print("Opening the file...")
target = open(filename, 'w')
print("Truncating the file. Goodbye!")
target.truncate()
print("Now I'm going to ask you for three lines.")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
print("I'm going to write these to the file.")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally, we close it")
target.close()
When I run this, it doesn't actually overwrite the file. It creates a new file that includes the three lines I entered. I know truncate is supposed to empty the file, so I don't know why ut's creating another file. I'm not sure what exactly is wrong, let me know. Thanks
Related
I can't open the file as a write file.
script = argv
filename = argv
print(f"We're going to erase {filename}. ")
print("If you don't want that, hit CTRL-C (^C). ")
print("If you do want that, hit RETURN. ")
input("?")
print("Opening the file...")
target = open(filename, 'w')
print("Truncating the file. Goodbye!")
target.truncate()
print("Now I'm going to ask you for three lines. ")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
print("I'm going to write these to the file. ")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally, we close it. ")
target.close()
It's giving this error:
line 14, in <module>
target = open(filename, 'w')
TypeError: expected str, bytes or os.PathLike object, not list
If I execute the code from terminal, It's giving me a syntax error for the last double quote of the first print statement.
line 6
print(f"We're going to erase {filename}. ")
^
SyntaxError: invalid syntax
To solve this I've changed the f-string to format.
print("We're going to erase {}. ".format(filename))
After I executed the code It gave me another error:
File "ex16.py", line 11, in <module>
input("?")
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
I don't know what to do.
I assume argv is sys.argv, and sys.argv is a list of the script name itself, and all arguments passed on the command line. Thus, you need to index it:
script = argv[0]
filename = argv[1]
I think you should add some checks to your program to check whether the correct amount of arguments have been passed, and the file really exists, etc., but that is up to you.
I'm learning python and trying to delete the contents of a life after the user input. for some reason it deletes the contents of the .txt before it asks for user input. Can't seem to work it out.
from sys import argv
import sys
script, filename = argv
def erase_contents(f):
user_input = input("> ")
if user_input == "yes":
current_file.truncate()
print("successfully deleted")
else:
sys.exit()
current_file = open(filename, "w+")
print(f"Now we are going to erase the contents of {filename}. type yes to delete.")
erase_contents(current_file)
You don't need to use truncate, because you are opening the file using w+ as the mode, which truncates the file immediately. You could use mode a instead, but really, there's no need to open the file at all until you determine that the user wants to truncate the file. You could just write
def erase_contents(fname):
user_input = input("> ")
if user_input == "yes":
with open(fname, "w"):
pass
else:
sys.exit()
print(f"Now we are going to erase the contents of {filename}. type yes to delete.")
erase_contents(filename)
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()
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
$
To Truncate just write:
f = open('filename', 'w')
f.close()
I feel like it's probably redundant with the two with statements, I wanted to add the if/else incase it didn't write the file for some reason it would notify me. How would I get this == "what is written in the file"
print("\tThis script is to erase and rewrite files")
filename = input("Filename: ")
print(f"\tWe're going to erase {filename}, then rewrite it.\n")
input("To cancel press CTRL-C\nTo continue press RETURN")
with open(filename, "w") as target:
print("Opening the file...")
print("Erasing the file. Goodbye!\n")
target.truncate()
rewrite = input("Time to rewrite your file, when you're finished press RETURN:\n ")
target.write(rewrite)
print("\n\tRewrite Confirmation:\n")
with open(filename) as this:
print('> ', this.read(), '\n')
if this == rewrite:
print("Rewrite complete.")
else:
print("Rewrite failed. Please try again.")
from sys import argv
script,filename = argv
print "Will truncate the file : %s" %filename
print "If you wish to continue press \"Return\" or press CNTRL-C"
raw_input("?")
target = open(filename,"w")
print "We are truncating the file"
target.truncate()
print "File is truncated"
print "Now enter the three lines to add into the file"
line1 = raw_input("Line_1 : ")
line2 = raw_input("Line_2 : ")
line3 = raw_input("Line_3 : ")
print "Adding these line is in progress"
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "Writter is completed"
target.close()
**print "Here is the new file :\n",open(target,mode='r', buffering=-1).read()**
target.close()
I am trying to truncate a file and then writting few lines in it , after that when Iclose the file and try to rreopen it , it's giving me the below error
Error is in the highlighted part .. can you please help me what could
be the error
You are getting this error because open is looking for a file name, and you're passing to it the file object itself.
From the docs on open function:
The first two arguments are the same as for stdio‘s fopen(): name is
the file name to be opened, and mode is a string indicating how the
file is to be opened.