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.")
Related
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()
The code below is what I have so far. When it writes to the .csv it overwrites what I had previously written in the file.How can I write to the file in such a way that it doesn't erase my previous text.(The objective of my code is to have a person enter their name and have the program remember them)
def main(src):
try:
input_file = open(src, "r")
except IOError as error:
print("Error: Cannot open '" + src + "' for processing.")
print("Welcome to Learner!")
print("What is your name? ")
name = input()
for line in input_file:
w = line.split(",")
for x in w:
if x.lower() == name.lower():
print("I remember you "+ name.upper())
else:
print("NO")
a = open("learner.csv", "w")
a.write(name)
a.close()
break
if __name__ == "__main__":
main("learner.csv")
You need to append to file the next time. This can be done by opening the file in append mode.
def addToFile(file, what):
f = open(file, 'a').write(what)
change open("learner.csv", "w") to open("learner.csv", "a")
The second parameter with open is the mode, w is write, a is append. With append it automatically seeks to the end of the file.
You'll want to open the file in append-mode ('a'), rathen than write-mode ('w'); the Python documentation explains the different modes available.
Also, you might want to consider using the with keyword:
It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.
>>> with open('/tmp/workfile', 'a') as f:
... f.write(your_input)
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
The code below is what I have so far. When it writes to the .csv it overwrites what I had previously written in the file.How can I write to the file in such a way that it doesn't erase my previous text.(The objective of my code is to have a person enter their name and have the program remember them)
def main(src):
try:
input_file = open(src, "r")
except IOError as error:
print("Error: Cannot open '" + src + "' for processing.")
print("Welcome to Learner!")
print("What is your name? ")
name = input()
for line in input_file:
w = line.split(",")
for x in w:
if x.lower() == name.lower():
print("I remember you "+ name.upper())
else:
print("NO")
a = open("learner.csv", "w")
a.write(name)
a.close()
break
if __name__ == "__main__":
main("learner.csv")
You need to append to file the next time. This can be done by opening the file in append mode.
def addToFile(file, what):
f = open(file, 'a').write(what)
change open("learner.csv", "w") to open("learner.csv", "a")
The second parameter with open is the mode, w is write, a is append. With append it automatically seeks to the end of the file.
You'll want to open the file in append-mode ('a'), rathen than write-mode ('w'); the Python documentation explains the different modes available.
Also, you might want to consider using the with keyword:
It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.
>>> with open('/tmp/workfile', 'a') as f:
... f.write(your_input)