Python function running truncate before user input - python

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)

Related

io.UnsupportedOpperation: read

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.

Getting python to write to new line in a FIle

I am trying to make a simple login system because I am bored and want to learn python, I am trying to store the usernames in a file but new usernames are just replacing the current one in the list.
#USENRAME UNENCRYPTED PASSWORD SYS
print ("WOuld you like to login or signup (login/signup)")
choice = input()
if choice == "signup":
print ("Can you enter your username please?")
username = input()
with open('username') as f:
if username in f.read():
print("That Username already exists")
else:
f= open("username","w+")
f.write(username + "\n")
f.close()
Say if the first username I enter is "Dave" and then I close the program, the next username I register with being "Harry" The "Harry" will just replace the "Dave" In line one of the "usernames" file.
You dont need to open your file twice, but when you open it the first time what you you want to be able to do is append to what is already there.
with open('username.txt','a+') as f:
if username in f.read():
print("That Username already exists")
else:
f.write(username + "\n")
Try reading this if you're unsure.
https://www.guru99.com/reading-and-writing-files-in-python.html

read and write multiple files separately from the console, python

I have a function which takes one compulsory file and other possible optional file. Currently the function can read and write single file from the user input. But I want to load and write as many files as user enters from the console input. For that, I want to define function for one compulsory filename and other as an optional parameters.
How do I ask users in console input to enter one compulsory file and other all possible optional filename (only if user wants) and read and write them separately in a function without mixing each other. I want to read and also write separately those all entered files.
Basically, I want to load all filenames which were entered by users in console input and write them separately in each new file.
Currently my function loads and read only one file from the user input.
def read_files(filename, *other):
with open(filename, 'rU') as f:
d = json.load(f)
Input for users:
if __name__ == '__main__':
filename = input('Enter your file name:')
#Here I am confused how do I ask the possible number of filename and How
#do i stop when the user enters all filename
other = input('Enter your other file name')
read_files(filename, )
You could hint that q for quit leads to stop adding further filenames:
if __name__ == '__main__':
filename = input('Enter your file name:')
other=[]
while True:
inp = input('Enter your other file name (q for quit)')
if inp == 'q':
break
else:
other.append(inp)
read_files(filename, other)
EDIT: Probably it's even more convenient to stop if nothing was entered, so the while loop would be:
while True:
inp = input('Enter your other file name (press ENTER for quit)')
if inp == '':
break
else:
other.append(inp)

Trying to figure out why this if statement wouldn't work

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.")

Basic Python Programming - writing data in a file

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.

Categories