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()
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 am making a program that gets a user input and determines if the user input is in either list 'yes' or 'no'. I want to use pickle to teach my program new forms of yes or no answers by asking the user when the code sees a new answer whether or not it is a 'yes' or 'no' type answer. I have an error, however, when I try to open the file that contains the lists. Here is my code:
import pickle
with open('yes.pkl', 'wb') as f:
yes = pickle.load(f)
with open('no.pkl', 'wb') as f:
no = pickle.load(f)
no = ["no", "never", "why should i", "nope", "noo", "nop", "n", "why", "no way", "not in a million years"]
yes = ["yes", "okay", "sure", "why not", "fine", "yah", "yeah", "y", "yee", "yesh", "yess", "yup", "yeppers", "yupperdoodle", "you bet"]
def closedq(x):
if x in no:
print("Meany.")
quit()
if x in yes:
print()
else:
time.sleep(1)
print()
print("I have not yet learned that term.")
time.sleep(1)
print("Is this a yes, or a no answer?")
yesno = input()
if yesno in yes:
yes.append(x)
with open('yes.pkl', 'wb') as f:
pickle.dump(yes, f)
if yesno in no:
no.append(x)
with open('no.pkl', 'wb') as f:
pickle.dump(no, f)
else:
print("Meany.")
quit()
print("Thank you for your input. ")
print()
print()
time.sleep(1)
print("Do you want to play a game?")
print()
play = input()
closedq(play)
print("Yay!")
The error I keep receiving is as follows.
Traceback (most recent call last):
File "main.py", line 3, in <module>
yes = pickle.load(f)
io.UnsupportedOperation: read
What am I doing wrong here?
Your code is opening the file in write-only mode, so reading from it to load the pickled data fails afterward. The issue is with this line (and the equivalent one for no):\
with open('yes.pkl', 'wb') as f:
For reading a file, you want mode 'rb', instead of 'wb'. Further down in the code, when you're writing to the file, you do correctly open for writing, but you don't want that up top.
Note that you may need extra logic in your code for when the file doesn't exist yet. Opening a non-existent file in write mode is fine, you just create it. But in read mode, the file needs to exist already. Initializing yes and no to empty lists might be what you want if the file doesn't exist yet, but I haven't fully examined your logic to know if that's the best approach.
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.")
I am just a beginner to programming and below is the code that I have written in python to save and edit a file but every time I run the programme it erases the previous save data, so I am confused why it's happening?
filename = raw_input("Please enter the file name to open it:\n")
doc = open (filename,'w')
print doc.read
text_input = raw_input("Please enter the data you want to enter in file:\n")
if text_input == "":
print "no input closing the programme."
else :
doc.write(text_input)
doc.close()
print "Printing the file:\n"
print doc.read
cl_file = raw_input("do you want to truncate file(y/n): ")
if cl_file == "y":
doc.truncate()
else :
print "Wrong input closing notepad"
exit()
You are opening the file in write mode, which truncates the file before writing to it. Instead of using open(filename, 'w') use open(filename, 'a'). The 'a' value tells the open function to use append mode so that writes to the file are added to the end of any existing content.
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