User defined writefile function won't save output to txt file - python

I've created two functions to read and write text files as a larger part of a caeser cipher program where I need to encode and decode content from and to different text files. These are:
def readfile(f):
try:
file_object = open(f, 'r+')
message = file_object.read()
file_object.close()
return message
except:
print("No such file or dictionary!")
quit()
and
def writefile(message):
try:
f = open("file", 'a')
f.write(message + '\n')
f.close()
except ValueError:
print("No such file or dictionary!")
quit()
except:
print("Input must be a string!")
quit()
The problem seems to be that my write function won't actually save the program's output to the next text file. I've been stumped for sometime, could use a hand.
EDIT Thanks Barmar! my write function was writing to a set file that didn't exist. This worked for me:
def writefile(message):
try:
f = open(input("Please enter a file for writing:"), 'w')
f.write(message + '\n')
f.close()
except ValueError:
print("The selected file cannot be open for writing!")
quit()
except:
quit()

Thanks Barmar! my write function was writing to a set file that didn't exist. This worked for me:
def writefile(message):
try:
f = open(input("Please enter a file for writing:"), 'w')
f.write(message + '\n')
f.close()
except ValueError:
print("The selected file cannot be open for writing!")
quit()
except:
quit()

Related

My program can only recognize the first pair of values in a pickle file

My program is a basic username password system I am working on. It allows you to store a username and password in a pickle file, and then log in with it. However, only the first "account" I make in the file works. I have looked at similar problems, but none of the solutions appear to work. Is there anything I am doing wrong, or need to add so all the accounts work? I have decoded the pickle file and all the accounts are there. I am a beginner programmer, so please give a simple explanation. Here is my code:
import pickle
import sys
l=0
answer="."
c=0
while c==0:
if not answer=="y" or not answer=="yes" or not answer=="Yes" or not answer=="n" or not answer=="No" or not answer=="no":
answer=input("have you already created an account?(y/n)")
if answer=="n" or answer=="no" or answer=="No" or answer=="y" or answer=="yes" or answer=="Yes":
c=1
if answer=="n" or answer=="no" or answer=="No":
p=1
while p==1:
UsernameSet=input("What will your username be? ")
fh = open("list.pkl", 'rb')
try:
Usernameport = pickle.load(fh)
except EOFError:
Usernameport = "."
if not (UsernameSet in Usernameport):
p=2
fh.close()
j=1
while j==1:
PasswordSet=input("What will your password be? ")
fh = open("list.pkl", 'rb')
try:
Passwordport = pickle.load(fh)
except EOFError:
Passwordport = "."
if not (PasswordSet in Passwordport):
if PasswordSet == UsernameSet:
print("Your username and password cannot be the same")
else:
j=2
print("You have created an account. please reload")
fh.close()
importthing = (UsernameSet,PasswordSet)
fh = open("list.pkl", 'ab')
pickle.dump(importthing, fh)
fh.close()
if answer=="y" or answer=="yes" or answer=="Yes":
p=1
while p==1:
Usernamething=input("Username: ")
fh = open("list.pkl", 'rb')
Usernamestuff = pickle.load(fh)
if (Usernamething in Usernamestuff):
p=2
l=Usernamething
fh.close()
j=1
while j==1:
Passwordthing=input("Password: ")
fh = open("list.pkl", 'rb')
Passwordstuff = pickle.load(fh)
if (Passwordthing in Passwordstuff):
j=2
print("you have logged in")
sys.exit()
fh.close()
Please review abarnert's answer at Pickle dump replaces current file data :
"when you append new dumps to the same file, you end up with a file made up of multiple separate values. If you only call load once, it's just going to load the first one. If you want to load all of them, you need to write code that does that. For example, you can load in a loop until EOFError."
def Load():
d = {}
with open('test.pkl', 'rb') as f:
while True:
try:
a = pickle.load(f)
except EOFError:
break
else:
d.update(a)
# do stuff with d

read/write a file input and insert a string

I need to write function which given a text file object open in read and write mode and a string, inserts the text of the string in the file at the current read/write position. In other words, the function writes the string in the file without overwriting the rest of it. When exiting the function, the new read/write position has to be exactly at the end of the newly inserted string.
The algorithm is simple; the function needs to:
read the content of the file starting at the current read/write position
write the given string at the same position step 1 started
write the content read at step 1. at the position where step 2. ended
reposition the read/write cursor at the same position step2. ended (and step 3. started)
If the argument file object is not readable or writable, the function should print a message and return immediately without changing anything.
This can be achieved by using the methods file object methods readable() and writable().
In the main script:
1- prompt the user for a filename
2- open the file in read-write mode. If the file is not found, print a message and exit the program
3- insert the filename as the first line of the file followed by an empty line
4- insert a line number and a space, at the beginning of each line of the original text.
I'm very confused on how to write the function and main body.
so far I only have
def openFile(fileToread):
print(file.read())
givefile = input("enter a file name: ")
try:
file = open(givefile, "r+")
readWriteFile = openFile(file)
except FileNotFoundError:
print("File does not exist")
exit(1)
print(givefile, "\n")
which is not a lot.
I need an output like this:
twinkle.txt
1 Twinkle, twinkle, little bat!
2 How I wonder what you're at!
3 Up above the world you fly,
4 Like a teatray in the sky.
the file used is a simple .txt file with the twinkle twinkle song
How can I do this?
Basic solution
give_file = input("enter a file name: ")
def open_file(file):
return file.read()
def save_file(file, content):
file.write(content)
try:
# Use this to get the data of the file
with open(give_file, "r") as fd:
file_content = open_file(fd)
except FileNotFoundError:
print("File does not exist")
exit(1)
# change the data
new_content = f'{give_file}\n\n{file_content}'
try:
# save the data
with open(give_file, "w") as fd:
save_file(fd, new_content)
except FileNotFoundError:
print("File does not exist")
exit(1)
This should give you the expected result.
I asked about the r+ and how to use it in this case. I got this answer:
reset the cursor to 0 should do the trick
my_fabulous_useless_string = 'POUET'
with open(path, 'r+') as fd:
content = fd.read()
fd.seek(0)
fd.write(f'{my_fabulous_useless_string}\n{content}')
so with your code it's:
give_file = input("enter a file name: ")
def open_file(file):
return file.read()
def save_file(file, content):
file.write(content)
try:
# Use this to get the data of the file
with open(give_file, "+r") as fd:
file_content = open_file(fd)
new_content = f'{give_file}\n\n{file_content}'
fd.seek(0)
save_file(fd, new_content)
except FileNotFoundError:
print("File does not exist")
exit(1)
A suggestion
Don't use function, it hide the fact that a method is used with some side-effects (move the cursor).
Instead, call the method directly, this is better:
give_file = input("enter a file name: ")
try:
# Use this to get the data of the file
with open(give_file, "+r") as fd:
file_content = fd.read()
new_content = f'{give_file}\n\n{file_content}'
fd.seek(0)
fd.write(new_content)
except FileNotFoundError:
print("File does not exist")
exit(1)
Or, with the basic solution and functions
def open_file(path):
with open(path, "r") as fd:
return fd.read()
def save_file(path, content):
with open(path, 'w') as fd:
fd.write(content)
# get file_name
file_name = input("enter a file name: ")
try:
# Use this to get the data of the file
file_content = open_file(file_name)
except FileNotFoundError:
print("File does not exist")
exit(1)
# change the data
new_content = f'{file_name}\n\n{file_content}'
# save the data
save_file(file_name, new_content)

Saving user output to file with while loop

I'm going through some exercises and I can't just figure this out.
Write a while loop that prompts users for their name. When they enter their name, print a greeting to the screen and add a line recording their visit in a file called guest_book.txt. Make sure each entry appears on a new line in the file.
Honestly, I spent way to much time on that and it seems like I'm not understanding the logic of working with files. I think the f.write should be directly under with open in order for the user input to be saved in the file but that's as much as I know. Can you please help me?
My attempts:
filename = 'guest_book.txt'
with open(filename, 'w') as f:
lines = input('Input your name to save in the file: ')
while True:
for line in lines:
f.write(input('Input your name to save in the file'))
I had some more hopes for the second one but still doesn't work.
filename = 'guest_book.txt'
prompt = "Input your name to be saved in guest book: "
active = True
with open(filename, 'w') as f:
while active:
message = f.write(input(prompt))
if message == 'quit':
break
else:
print(message)
A bit of rejigging will get the code as you've written it to work. The main issue is that you can't use the output of f.write() as the value of message, as it doesn't contain the message, it contains the number of characters written to the file, so it will never contain quit. Also, you want to do the write after you have checked for quit otherwise you will write quit to the file.
filename = 'guest_book.txt'
prompt = "Input your name to be saved in guest book: "
active = True
with open(filename, 'w') as f:
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
f.write(message + '\n')
print(message)
Note: I have changed the break to active = False as you have written it as while active:, but you would have been fine with just while True: and break
filename = 'guest_book.txt'
prompt = "Input your name to be saved in guest book: "
active = True
with open(filename, 'w') as f:
while active:
message = input(prompt)
if message == 'quit':
break
else:
print(message)
f.write(message + '\n')
This might work. Assigning message = f.write(...) will make its value the return value of f.write().
Try this..
filename = 'guest_book.txt'
name = ''
with open(filename, 'w') as f:
while name != 'quit':
name = input('Input your name to save in the file: ')
if(name == 'quit'):
break
f.write(name + '\n')
You can use open(filename, 'a') when a stands for append that way you can append a new line to the file each loop iteration.
see: How do you append to a file in Python?
To learn about file handling see: https://www.w3schools.com/python/python_file_handling.asp
Good luck!
For anyone wondering how to solve the whole thing. We're using append instead of write in order to keep all the guests that have been using the programme in the past. Write would override the file.
filename = 'guest_book.txt'
print("Enter 'quit' when you are finished.")
while True:
name = input("\nWhat's your name? ")
if name == 'quit':
break
else:
with open(filename, 'a') as f:
f.write(name + "\n")
print(f"Hi {name}, you've been added to the guest book.")

Cannot write to a file using open()

This code always goes into the except section
to_add = "text to add"
try:
with open ('text.txt','r') as txt:
txt.write('text to add'+to_add')
print("done")
except:
to_add== 0 or None or ''
print("unable to write to file")
Open file as 'w' not 'r'
with open('test.txt', 'w') as txt:
There are a couple fixes required.
try with this snippet:
to_add = "text to add"
try:
with open ('text.txt', 'w') as txt: # change the mode to write
txt.write('text to add' + to_add) # removing the last char '
print("done")
except NameError:
print("unable to write to file")

Function that creates a new file

I want to create a function, user_dialogue() that asks for the name of two files. This function needs to handle Errors such as IOError. The two files should then run through another function I created, that is called encryption_function.
The program should work like this:
Name of new encrypted file: out_file.txt
Name of file to be encrypted:blah.txt
That resulted in an error! Please try again.
Name of file to be encrypted: my file.csv
Encryption completed!
This is my code so far:
def user_dialogue():
file1 = open(input("New name of file: "), 'w')
done = False
while not done:
try:
file2 = open(input("Name of file that you want to encrypt: "), 'r')
except IOError as error:
print("File doesn't exist! The error is of the type: ", error)
else:
file2.close()
done = True
encrypt_file(file2,file1)
user_dialogue()
And this is my function encrypt_file:
def encrypt_file(in_file, out_file):
fr = open(in_file, 'r')
fileread = fr.read()
encryptedfile = text_encryption_function.encrypt(fileread)
fr.close()
fw = open(out_file, 'a+')
fw.write(encryptedfile)
fw.close()
return in_file, out_file
For some reason the code doesn't work! Any help please?
Using context manager with:
def user_dialogue():
try:
with open(input("Name of file that you want to encrypt: "), 'r') as file2:
try:
with open(input("New name of file(encrypted): "), 'w') as file1:
encrypt_file(file2, file1)
except IOError as e3:
print('No access')
except FileNotFoundError as e1:
print('No such file')
except IOError as e2:
print('No access')
def encrypt_file(in_file, out_file):
fileread = in_file.read()
encryptedfile = text_encryption_function.encrypt(fileread)
out_file.write(encryptedfile)
Using try/except:
def user_dialogue():
try:
file2 = open(input("Name of file that you want to encrypt: "), 'r')
try:
file1 = open(input("New name of file(encrypted): "), 'w')
encrypt_file(file2, file1)
except IOError as e3:
print('No access')
else:
file1.close()
except FileNotFoundError as e1:
print('No such file')
except IOError as e2:
print('No access')
else:
file2.close()
def encrypt_file(in_file, out_file):
fileread = in_file.read()
encryptedfile = text_encryption_function.encrypt(fileread)
out_file.write(encryptedfile)

Categories